Azureでメールが送れるサービスが使えるようになったとのことで試してみました。
Azureでリソースを作成する
Azure Portalから以下3つのリソースを作成します。
- Communication Services
- Email Communication Services
- ドメイン
Communication Servicesの作成
Azure Portalからポチポチとリソース作成をしていきます。
Communication Servicesのデータの場所はAsia Pacificを選択しました。この後に作成するEmail Communication Servicesでも同様の場所を選択する必要があります。
Email Communication Servicesの作成
こちらも同様にデータの場所でAsia Pacificを選択し、作成していきます。
ドメイン
Email Communication Servicesのデプロイ完了後にリソースに移動すると、ドメインを追加しましょうとなっているので無料のAzureサブドメインを追加しました。
ドメインの接続
作成したCommunication Servicesのリソースに移動し、ドメインの接続を行います。
電子メールサービスは作成したEmail Communication Servicesのリソースを選択し、確認済みのドメインは1つ前に作成したドメインを選択します。
接続文字列の確認
Communication Servicesのリソースに移動し、キーから接続文字列を確認します。
この後にプログラムからメールを送信するときに使うのでコピーしておきます。
プログラムからメールを送信する
コンソールアプリでメールを送信してみます。 Azure.Communication.EmailというNugutパッケージを追加します。
dotnet add package Azure.Communication.Email
メールを送信するプログラムはこのようになりました。
using Azure; using Azure.Communication.Email; // Azure Communication Servicesから取得した接続文字列を使用 var connectionString = "************"; var emailClient = new EmailClient(connectionString); var subject = "Welcome to Azure Communication Service Email APIs."; var htmlContent = "<html><body><h1>Quick send email test</h1><br/><h4>This email message is sent from Azure Communication Service Email.</h4><p>This mail was sent using .NET SDK!!</p></body></html>"; // 取得したドメイン名を使用 var sender = "donotreply@********"; // 送信先のメールアドレスを設定 var recipient = "hogehoge@gmail.com"; try { var emailSendOperation = await emailClient.SendAsync( WaitUntil.Completed, sender, recipient, subject, htmlContent); var statusMonitor = emailSendOperation.Value; Console.WriteLine($"Email Sent. Status = {emailSendOperation.Value.Status}"); var operationId = emailSendOperation.Id; Console.WriteLine($"Email operation id = {operationId}"); } catch (RequestFailedException ex) { Console.WriteLine($"Email send operation failed with error code: {ex.ErrorCode}, message: {ex.Message}"); }
実行後にメールを確認するとちゃんと届いていました。
料金感
この記事を書いた時点ではメール1通あたり¥0.03513が発生するようです。