.NET 用 Azure Communication Email クライアント ライブラリ - バージョン 1.0.1

このパッケージには、Email用の C# SDK for Azure Communication Servicesが含まれています。

ソースコード | パッケージ (NuGet) | 製品ドキュメント

作業の開始

パッケージをインストールする

NuGet を使用して .NET 用の Azure Communication Email クライアント ライブラリをインストールします。

dotnet add package Azure.Communication.Email

前提条件

Azure サブスクリプションCommunication Service リソース、およびアクティブなドメインを持つEmail通信リソースが必要です。

これらのリソースを作成するには、Azure PortalAzure PowerShell、または .NET 管理クライアント ライブラリを使用できます。

主要な概念

EmailClient は、電子メール メッセージを送信する機能を提供します。

ステートメントの使用

using Azure.Communication.Email;

クライアントを認証する

Emailクライアントは、Azure Portal の Azure Communication Resource から取得した接続文字列を使用して認証できます。

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

または、Emailクライアントは、有効なトークン資格情報を使用して認証することもできます。 この認証方法を使用する場合、AZURE_CLIENT_SECRETAZURE_CLIENT_IDAZURE_TENANT_ID の各環境変数が設定されている必要があります。

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

状態の自動ポーリングを使用して簡単な電子メール メッセージを送信する

電子メール メッセージを送信するには、 から または 関数のSend単純なオーバーロードをEmailClient呼び出SendAsyncします。

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

状態を手動でポーリングして簡単な電子メール メッセージを送信する

電子メール メッセージを送信するには、 から または 関数のSend単純なオーバーロードをEmailClient呼び出SendAsyncします。

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

その他のオプションを含むメール メッセージを送信する

電子メール メッセージを送信するには、 パラメーターを受け取る から または SendAsync 関数のSendEmailClientオーバーロードをEmailMessage呼び出します。

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

複数の受信者にメール メッセージを送信する

複数の受信者に電子メール メッセージを送信するには、レシピの種類ごとに オブジェクトを オブジェクトにEmailRecipient追加EmailAddressします。

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

添付ファイル付きでメールを送信する

Azure Communication Servicesは、添付ファイルを含むメールの送信をサポートしています。

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

トラブルシューティング

RequestFailedExceptionは、失敗した要求に対するサービス応答としてスローされます。 例外には、サービスから返された応答コードに関する情報が含まれています。

次のステップ

共同作成

このプロジェクトでは、共同作成と提案を歓迎しています。 ほとんどの共同作成では、共同作成者使用許諾契約書 (CLA) にご同意いただき、ご自身の共同作成内容を使用する権利を Microsoft に供与する権利をお持ちであり、かつ実際に供与することを宣言していただく必要があります。 詳細については、「 cla.microsoft.com」を参照してください。

このプロジェクトでは、Microsoft オープン ソースの倫理規定を採用しています。 詳しくは、「Code of Conduct FAQ (倫理規定についてよくある質問)」を参照するか、opencode@microsoft.com 宛てに質問またはコメントをお送りください。