Biblioteca de cliente do Azure Communication Email para .NET – versão 1.0.0

Este pacote contém um SDK C# para Azure Communication Services para Email.

Código fonte | Pacote (NuGet) | Documentação do produto

Introdução

Instalar o pacote

Instale a biblioteca de cliente do Azure Communication Email para .NET com NuGet:

dotnet add package Azure.Communication.Email

Pré-requisitos

Precisa de uma subscrição do Azure, de um Recurso do Serviço de Comunicação e de um Recurso de Comunicação Email com um Domínio ativo.

Para criar estes recursos, pode utilizar o Portal do Azure, o Azure PowerShell ou a biblioteca de cliente de gestão .NET.

Conceitos-chave

EmailClient fornece a funcionalidade para enviar mensagens de e-mail.

Utilizar instruções

using Azure.Communication.Email;

Autenticar o cliente

Email clientes podem ser autenticados com a cadeia de ligação adquirida a partir de um Recurso de Comunicação do Azure no Portal do Azure.

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

Em alternativa, Email clientes também podem ser autenticados com uma credencial de token válida. Com esta opção, AZURE_CLIENT_SECRETe AZURE_TENANT_IDAZURE_CLIENT_ID as variáveis de ambiente têm de ser configuradas para autenticação.

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

Exemplos

Enviar uma mensagem de e-mail simples com consulta automática para o estado

Para enviar uma mensagem de e-mail, chame a sobrecarga SendSendAsync ou função simples da 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}");
}

Enviar uma mensagem de e-mail simples com consulta manual para o estado

Para enviar uma mensagem de e-mail, chame a sobrecarga SendSendAsync ou função simples da 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}");

Enviar uma mensagem de e-mail com mais opções

Para enviar uma mensagem de e-mail, chame a sobrecarga de Send ou SendAsync função a EmailClient partir do parâmetro que utiliza um EmailMessage parâmetro.

// 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}");
}

Enviar uma mensagem de e-mail a vários destinatários

Para enviar uma mensagem de e-mail a vários destinatários, adicione um EmailAddress objeto para cada tipo de receita ao EmailRecipient objeto.

// 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}");
}

Enviar e-mail com anexos

Azure Communication Services suporte para o envio de e-mails com anexos.

// 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}");
}

Resolução de problemas

Um RequestFailedException é emitido como uma resposta de serviço para quaisquer pedidos sem êxito. A exceção contém informações sobre que código de resposta foi devolvido do serviço.

Passos seguintes

Contribuir

Agradecemos todas as contribuições e sugestões para este projeto. A maioria das contribuições requerem que celebre um Contrato de Licença de Contribuição (CLA) no qual se declare que tem o direito de conceder e que, na verdade, concede-nos os direitos para utilizar a sua contribuição. Para obter detalhes, visite cla.microsoft.com.

Este projeto adotou o Microsoft Open Source Code of Conduct (Código de Conduta do Microsoft Open Source). Para obter mais informações, consulte as FAQ do Código de Conduta ou o contacto opencode@microsoft.com com quaisquer perguntas ou comentários adicionais.