Libreria client di Comunicazione di Azure Email per .NET - versione 1.0.0

Questo pacchetto contiene un SDK C# per Servizi di comunicazione di Azure per Email.

Codice | sorgente Pacchetto (NuGet) | Documentazione del prodotto

Introduzione

Installare il pacchetto

Installare la libreria client di Comunicazione di Azure Email per .NET con NuGet:

dotnet add package Azure.Communication.Email

Prerequisiti

È necessaria una sottoscrizione di Azure, una risorsa del serviziodi comunicazione e una risorsa di comunicazione Email con un dominio attivo.

Per creare queste risorse, è possibile usare il portale di Azure, il Azure PowerShell o la libreria client di gestione .NET.

Concetti chiave

EmailClient fornisce la funzionalità per inviare messaggi di posta elettronica.

Uso delle istruzioni

using Azure.Communication.Email;

Autenticare il client

Email client possono essere autenticati usando la stringa di connessione acquisita da una risorsa di comunicazione di Azure nel portale di Azure.

var connectionString = "<connection_string>"; // Find your Communication Services resource in the Azure portal
EmailClient emailClient = new EmailClient(connectionString);

In alternativa, i client Email possono essere autenticati usando una credenziale del token valida. Con questa opzione, AZURE_CLIENT_SECRETe AZURE_CLIENT_IDAZURE_TENANT_ID le variabili di ambiente devono essere configurate per l'autenticazione.

string endpoint = "<endpoint_url>";
TokenCredential tokenCredential = new DefaultAzureCredential();
tokenCredential = new DefaultAzureCredential();
EmailClient emailClient = new EmailClient(new Uri(endpoint), tokenCredential);

Esempio

Inviare un messaggio di posta elettronica semplice con polling automatico per lo stato

Per inviare un messaggio di posta elettronica, chiamare il semplice overload di Send o SendAsync funzione dall'oggetto EmailClient.

try
{
    var emailSendOperation = emailClient.Send(
        wait: WaitUntil.Completed,
        senderAddress: "<Send email address>" // The email address of the domain registered with the Communication Services resource
        recipientAddress: "<recipient email address>"
        subject: "This is the subject",
        htmlContent: "<html><body>This is the html body</body></html>");
    Console.WriteLine($"Email Sent. Status = {emailSendOperation.Value.Status}");

    /// Get the OperationId so that it can be used for tracking the message for troubleshooting
    string operationId = emailSendOperation.Id;
    Console.WriteLine($"Email operation id = {operationId}");
}
catch ( RequestFailedException ex )
{
    /// OperationID is contained in the exception message and can be used for troubleshooting purposes
    Console.WriteLine($"Email send operation failed with error code: {ex.ErrorCode}, message: {ex.Message}");
}

Inviare un messaggio di posta elettronica semplice con il polling manuale per lo stato

Per inviare un messaggio di posta elettronica, chiamare il semplice overload di Send o SendAsync funzione dall'oggetto EmailClient.

/// Send the email message with WaitUntil.Started
var emailSendOperation = await emailClient.SendAsync(
    wait: WaitUntil.Started,
    senderAddress: "<Send email address>" // The email address of the domain registered with the Communication Services resource
    recipientAddress: "<recipient email address>"
    subject: "This is the subject",
    htmlContent: "<html><body>This is the html body</body></html>");

/// Call UpdateStatus on the email send operation to poll for the status
/// manually.
try
{
    while (true)
    {
        await emailSendOperation.UpdateStatusAsync();
        if (emailSendOperation.HasCompleted)
        {
            break;
        }
        await Task.Delay(100);
    }

    if (emailSendOperation.HasValue)
    {
        Console.WriteLine($"Email queued for delivery. Status = {emailSendOperation.Value.Status}");
    }
}
catch (RequestFailedException ex)
{
    Console.WriteLine($"Email send failed with Code = {ex.ErrorCode} and Message = {ex.Message}");
}

/// Get the OperationId so that it can be used for tracking the message for troubleshooting
string operationId = emailSendOperation.Id;
Console.WriteLine($"Email operation id = {operationId}");

Inviare un messaggio di posta elettronica con altre opzioni

Per inviare un messaggio di posta elettronica, chiamare l'overload di Send o SendAsync la funzione dall'oggetto EmailClient che accetta un EmailMessage parametro.

// Create the email content
var emailContent = new EmailContent("This is the subject")
{
    PlainText = "This is the body",
    Html = "<html><body>This is the html body</body></html>"
};

// Create the EmailMessage
var emailMessage = new EmailMessage(
    senderAddress: "<Send email address>" // The email address of the domain registered with the Communication Services resource
    recipientAddress: "<recipient email address>"
    content: emailContent);

try
{
    var emailSendOperation = emailClient.Send(
        wait: WaitUntil.Completed,
        message: emailMessage);
    Console.WriteLine($"Email Sent. Status = {emailSendOperation.Value.Status}");

    /// Get the OperationId so that it can be used for tracking the message for troubleshooting
    string operationId = emailSendOperation.Id;
    Console.WriteLine($"Email operation id = {operationId}");
}
catch ( RequestFailedException ex )
{
    /// OperationID is contained in the exception message and can be used for troubleshooting purposes
    Console.WriteLine($"Email send operation failed with error code: {ex.ErrorCode}, message: {ex.Message}");
}

Inviare un messaggio di posta elettronica a più destinatari

Per inviare un messaggio di posta elettronica a più destinatari, aggiungere un EmailAddress oggetto per ogni tipo di ricettazione all'oggetto EmailRecipient .

// Create the email content
var emailContent = new EmailContent("This is the subject")
{
    PlainText = "This is the body",
    Html = "<html><body>This is the html body</body></html>"
};

// Create the To list
var toRecipients = new List<EmailAddress>
{
    new EmailAddress(
        address: "<recipient email address>"
        displayName: "<recipient displayname>"
    new EmailAddress(
        address: "<recipient email address>"
        displayName: "<recipient displayname>"
};

// Create the CC list
var ccRecipients = new List<EmailAddress>
{
    new EmailAddress(
        address: "<recipient email address>"
        displayName: "<recipient displayname>"
    new EmailAddress(
        address: "<recipient email address>"
        displayName: "<recipient displayname>"
};

// Create the BCC list
var bccRecipients = new List<EmailAddress>
{
    new EmailAddress(
        address: "<recipient email address>"
        displayName: "<recipient displayname>"
    new EmailAddress(
        address: "<recipient email address>"
        displayName: "<recipient displayname>"
};

var emailRecipients = new EmailRecipients(toRecipients, ccRecipients, bccRecipients);

// Create the EmailMessage
var emailMessage = new EmailMessage(
    senderAddress: "<Send email address>" // The email address of the domain registered with the Communication Services resource
    emailRecipients,
    emailContent);

try
{
    EmailSendOperation emailSendOperation = emailClient.Send(WaitUntil.Completed, emailMessage);
    Console.WriteLine($"Email Sent. Status = {emailSendOperation.Value.Status}");

    /// Get the OperationId so that it can be used for tracking the message for troubleshooting
    string operationId = emailSendOperation.Id;
    Console.WriteLine($"Email operation id = {operationId}");
}
catch ( RequestFailedException ex )
{
    /// OperationID is contained in the exception message and can be used for troubleshooting purposes
    Console.WriteLine($"Email send operation failed with error code: {ex.ErrorCode}, message: {ex.Message}");
}

Inviare un messaggio di posta elettronica con allegati

Servizi di comunicazione di Azure supportare l'invio di messaggi di posta elettronica con allegati.

// Create the EmailMessage
var emailMessage = new EmailMessage(
    senderAddress: "<Send email address>" // The email address of the domain registered with the Communication Services resource
    recipientAddress: "<recipient email address>"
    content: emailContent);

var filePath = "<path to your file>";
var attachmentName = "<name of your attachment>";
var contentType = MediaTypeNames.Text.Plain;

var content = new BinaryData(System.IO.File.ReadAllBytes(filePath));
var emailAttachment = new EmailAttachment(attachmentName, contentType, content);

emailMessage.Attachments.Add(emailAttachment);

try
{
    EmailSendOperation emailSendOperation = emailClient.Send(WaitUntil.Completed, emailMessage);
    Console.WriteLine($"Email Sent. Status = {emailSendOperation.Value.Status}");

    /// Get the OperationId so that it can be used for tracking the message for troubleshooting
    string operationId = emailSendOperation.Id;
    Console.WriteLine($"Email operation id = {operationId}");
}
catch ( RequestFailedException ex )
{
    /// OperationID is contained in the exception message and can be used for troubleshooting purposes
    Console.WriteLine($"Email send operation failed with error code: {ex.ErrorCode}, message: {ex.Message}");
}

Risoluzione dei problemi

Viene RequestFailedException generata una risposta come servizio per eventuali richieste non riuscite. L'eccezione contiene informazioni sul codice di risposta restituito dal servizio.

Passaggi successivi

Contributo

In questo progetto sono benvenuti i contributi e i suggerimenti. Per la maggior parte dei contenuti è necessario sottoscrivere un contratto di licenza di collaborazione (CLA, Contributor License Agreement) che stabilisce che l'utente ha il diritto di concedere, e di fatto concede a Microsoft i diritti d'uso del suo contributo. Per informazioni dettagliate, visitare cla.microsoft.com.

Questo progetto ha adottato il Codice di comportamento di Microsoft per l'open source. Per altre informazioni, vedere Code of Conduct FAQ (Domande frequenti sul Codice di comportamento Open Source di Microsoft) oppure contattare opencode@microsoft.com per eventuali altre domande o commenti.