Share via


Azure Communication Email-Clientbibliothek für .NET – Version 1.0.1

Dieses Paket enthält ein C#-SDK für Azure Communication Services für Email.

Quellcode | Paket (NuGet) | Produktdokumentation

Erste Schritte

Installieren des Pakets

Installieren Sie die Azure Communication Email-Clientbibliothek für .NET mit NuGet:

dotnet add package Azure.Communication.Email

Voraussetzungen

Sie benötigen ein Azure-Abonnement, eine Communication Service-Ressource und eine Email Kommunikationsressource mit einer aktiven Domäne.

Zum Erstellen dieser Ressource können Sie das Azure-Portal, die Azure PowerShell oder die .NET-Verwaltungsclientbibliothek verwenden.

Wichtige Begriffe

EmailClient stellt die Funktionalität zum Senden von E-Mail-Nachrichten bereit.

Verwenden von Anweisungen

using Azure.Communication.Email;

Authentifizieren des Clients

Email Clients können mithilfe der Verbindungszeichenfolge authentifiziert werden, die von einer Azure-Kommunikationsressource im Azure-Portal abgerufen wurde.

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

Alternativ können Email Clients auch mit gültigen Tokenanmeldeinformationen authentifiziert werden. Mit dieser Option müssen die Umgebungsvariablen AZURE_CLIENT_SECRET, AZURE_CLIENT_ID und AZURE_TENANT_ID für die Authentifizierung eingerichtet werden.

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

Beispiele

Senden einer einfachen E-Mail-Nachricht mit automatischer Abfrage für status

Um eine E-Mail-Nachricht zu senden, rufen Sie die einfache Überladung von Send oder SendAsync von aus auf 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}");
}

Senden einer einfachen E-Mail-Nachricht mit manueller Abfrage für status

Um eine E-Mail-Nachricht zu senden, rufen Sie die einfache Überladung von Send oder SendAsync von aus auf 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}");

Senden einer E-Mail-Nachricht mit weiteren Optionen

Um eine E-Mail-Nachricht zu senden, rufen Sie die Überladung von Send oder SendAsync von der-Funktion auf, die EmailClient einen EmailMessage Parameter akzeptiert.

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

Senden einer E-Mail-Nachricht an mehrere Empfänger

Um eine E-Mail-Nachricht an mehrere Empfänger zu senden, fügen Sie dem EmailRecipient Objekt ein EmailAddress Objekt für jeden Rezepttyp hinzu.

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

E-Mail mit Anhang senden

Azure Communication Services unterstützen das Senden von E-Mails mit Anlagen.

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

Problembehandlung

Ein RequestFailedException wird als Dienstantwort für alle nicht erfolgreichen Anforderungen ausgelöst. Die Ausnahme enthält Informationen darüber, welcher Antwortcode vom Dienst zurückgegeben wurde.

Nächste Schritte

Mitwirken

Beiträge und Vorschläge für dieses Projekt sind willkommen. Most contributions require you to agree to a Contributor License Agreement (CLA) declaring that you have the right to, and actually do, grant us the rights to use your contribution. Weitere Informationen finden Sie unter cla.microsoft.com.

Für dieses Projekt gelten die Microsoft-Verhaltensregeln für Open Source (Microsoft Open Source Code of Conduct). Weitere Informationen finden Sie in den häufig gestellten Fragen zum Verhaltenskodex. Sie können sich auch an opencode@microsoft.com wenden, wenn Sie weitere Fragen oder Anmerkungen haben.