Amazon v2 を使用した raw E SES API メールの送信 - Amazon Simple Email Service

翻訳は機械翻訳により提供されています。提供された翻訳内容と英語版の間で齟齬、不一致または矛盾がある場合、英語版が優先します。

Amazon v2 を使用した raw E SES API メールの送信

Amazon v2 SendEmailオペレーションを SES API として指定されたコンテンツタイプで使用rawして、raw E メール形式を使用してカスタマイズされたメッセージを受信者に送信できます。

E メールヘッダーフィールドについて

Simple Mail Transfer Protocol (SMTP) は、メールエンベロープとそのパラメータの一部を定義することで、E メールメッセージの送信方法を指定しますが、メッセージの内容自体は関係ありません。代わりに、インターネットメッセージ形式 (RFC 5322) は、メッセージの作成方法を定義します。

Internet Message Format の仕様に従って、すべてのメッセージ E メールはヘッダーと本文から構成されます。ヘッダーはメッセージのメタデータで構成され、本文にメッセージそのものが含まれます。E メールヘッダーと本文の詳細については、「Amazon SESのE メール形式」を参照してください。

の使用 MIME

SMTP プロトコルは、もともと 7 ビットASCII文字のみを含む E メールメッセージを送信するように設計されていました。この仕様では、非ASCIIテキストエンコーディング (Unicode など)、バイナリコンテンツ、または添付ファイルではSMTP不十分です。Multipurpose Internet Mail Extensions 標準 (MIME) は、 を使用して他の多くの種類のコンテンツを送信できるように開発されましたSMTP。

MIME 標準は、メッセージ本文を複数の部分に分割し、各パートで何をするかを指定することで機能します。例えば、E メールメッセージ本文の一部はプレーンテキストで、別の部分は ですHTML。さらに、 MIMEでは、E メールメッセージに 1 つ以上の添付ファイルを含めることができます。メッセージの受取人は、E メールクライアント内から添付ファイルを見たり、保存したりできます。

メッセージヘッダーとコンテンツとは空白行で分離されます。E メールの各パートは、boundary で分離されます。boundary は、各パートの開始と終了を示す文字列です。

次の例のマルチパートメッセージには、テキストとHTMLパート、および添付ファイルが含まれています。添付ファイルは添付ファイルヘッダーのすぐ下に配置する必要があります。ほとんどの場合、この例のように base64 でエンコードされます。

From: "Sender Name" <sender@example.com> To: recipient@example.com Subject: Customer service contact info Content-Type: multipart/mixed; boundary="a3f166a86b56ff6c37755292d690675717ea3cd9de81228ec2b76ed4a15d6d1a" --a3f166a86b56ff6c37755292d690675717ea3cd9de81228ec2b76ed4a15d6d1a Content-Type: multipart/alternative; boundary="sub_a3f166a86b56ff6c37755292d690675717ea3cd9de81228ec2b76ed4a15d6d1a" --sub_a3f166a86b56ff6c37755292d690675717ea3cd9de81228ec2b76ed4a15d6d1a Content-Type: text/plain; charset=iso-8859-1 Content-Transfer-Encoding: quoted-printable Please see the attached file for a list of customers to contact. --sub_a3f166a86b56ff6c37755292d690675717ea3cd9de81228ec2b76ed4a15d6d1a Content-Type: text/html; charset=iso-8859-1 Content-Transfer-Encoding: quoted-printable <html> <head></head> <body> <h1>Hello!</h1> <p>Please see the attached file for a list of customers to contact.</p> </body> </html> --sub_a3f166a86b56ff6c37755292d690675717ea3cd9de81228ec2b76ed4a15d6d1a-- --a3f166a86b56ff6c37755292d690675717ea3cd9de81228ec2b76ed4a15d6d1a Content-Type: text/plain; name="customers.txt" Content-Description: customers.txt Content-Disposition: attachment;filename="customers.txt"; creation-date="Sat, 05 Aug 2017 19:35:36 GMT"; Content-Transfer-Encoding: base64 SUQsRmlyc3ROYW1lLExhc3ROYW1lLENvdW50cnkKMzQ4LEpvaG4sU3RpbGVzLENhbmFkYQo5MjM4 OSxKaWUsTGl1LENoaW5hCjczNCxTaGlybGV5LFJvZHJpZ3VleixVbml0ZWQgU3RhdGVzCjI4OTMs QW5heWEsSXllbmdhcixJbmRpYQ== --a3f166a86b56ff6c37755292d690675717ea3cd9de81228ec2b76ed4a15d6d1a--

メッセージのコンテンツタイプが multipart/mixed であることから、メッセージに多数のパートがあり (この例では、本文および添付ファイル)、受信するクライアントは各パートを別々に扱う必要があることがわかります。

本文セクション内に入れ子になっているのは、multipart/alternative コンテンツタイプを使用する 2 番目のパートです。このコンテンツタイプは、各パートに同じコンテンツの代替バージョン (この場合はテキストHTMLバージョンと バージョン) が含まれていることを示します。受信者の E メールクライアントがHTMLコンテンツを表示できる場合は、メッセージ本文HTMLのバージョンが表示されます。受信者の E メールクライアントがHTMLコンテンツを表示できない場合、メッセージ本文のプレーンテキストバージョンが表示されます。

メッセージの両方のバージョンには添付ファイルも含まれます (この場合、一部の顧客名を含むショートテキストファイル)。

この例では、MIME別のパート内にパートをネストする場合、ネストされたパートboundaryは親パートの パラメータとは異なるboundaryパラメータを使用する必要があります。これらの境界は固有の文字列でなければなりません。MIME 部分間の境界を定義するには、2 つのハイフン (--) を入力し、その後に境界文字列を入力します。MIME パートの最後に、境界文字列の先頭と末尾の両方に 2 つのハイフンを配置します。

注記

メッセージには 500 個を超えるMIME部分を含めることはできません。

MIME エンコード

古いシステムとの互換性を維持するために、Amazon は 2821 で定義されている SMTP の 7 ビットASCII制限SESを尊重します。 RFC 以外のASCII文字を含むコンテンツを送信する場合は、それらの文字を 7 ビットASCII文字を使用する形式にエンコードする必要があります。

E メールアドレス

E メールアドレス文字列は 7 ビット である必要がありますASCII。送信先または送信元の E メールアドレス内で、ドメインの部分に Unicode 文字が含まれる場合は、Punycode を使用してドメインをエンコードする必要があります。Punycode は E メールアドレスのローカル部分 (@ 記号の前の部分) では許可されていません。また、「差出人」名にも許可されていません。「フレンドリ元」名に Unicode 文字を使用する場合は、「」で説明されているように、エンコードされた単語構文を使用して「フレンドリ元」名をMIMEエンコードする必要がありますAmazon v2 を使用した raw E SES API メールの送信。Punycode の詳細については、RFC「3492」を参照してください。

注記

このルールは、メッセージヘッダーではなく、メッセージエンベロープで指定する E メールアドレスにのみ適用されます。Amazon v2 SendEmailオペレーションを使用する場合、 Sourceおよび SES API Destinationsパラメータで指定したアドレスによって、それぞれエンベロープ送信者と受信者が定義されます。

E メールヘッダー

メッセージヘッダーをエンコードするには、MIMEエンコードされた単語構文を使用します。MIME エンコードされた単語構文は、次の形式を使用します。

=?charset?encoding?encoded-text?=

encodingの値は Qまたは Bとなります。エンコードの値が Q の場合、値 encoded-text には Q エンコードを使用する必要があります。エンコードの値が B の場合、encoded-text の値には base64 エンコードを使用する必要があります。

たとえば、「Як ти поживаєш?」を使用する場合 E メールの件名に次のエンコードのいずれかを使用することができます。

  • Q エンコード

    =?utf-8?Q?=D0=AF=D0=BA_=D1=82=D0=B8_=D0=BF=D0=BE=D0=B6=D0=B8=D0=B2=D0=B0=D1=94=D1=88=3F?=
  • Base64 エンコード

    =?utf-8?B?0K/QuiDRgtC4INC/0L7QttC40LLQsNGU0Yg/?=

Q エンコードの詳細については、RFC「2047」を参照してください。base64 エンコーディングの詳細については、RFC「2045」を参照してください。

メッセージ本文

メッセージの本文をエンコードするには、quoted-printable エンコードまたは base64 エンコードを使用できます。次に、Content-Transfer-Encoding ヘッダーを使用して、使用するエンコードスキームを指定します。

たとえば、メッセージの本文に次のテキストが含まれているとします。

१९७२ मे रे टॉमलिंसन ने पहला ई-मेल संदेश भेजा | रे टॉमलिंसन ने ही सर्वप्रथम @ चिन्ह का चयन किया और इन्ही को ईमेल का आविष्कारक माना जाता है

base64 エンコードを使用してこのテキストをエンコードする場合、最初に以下のヘッダーを指定します。

Content-Transfer-Encoding: base64

次に、E メールの本文セクションに、base64 でエンコードされたテキストを含めます。

4KWn4KWv4KWt4KWoIOCkruClhyDgpLDgpYcg4KSf4KWJ4KSu4KSy4KS/4KSC4KS44KSoIOCkqOCl hyDgpKrgpLngpLLgpL4g4KSILeCkruClh+CksiDgpLjgpILgpKbgpYfgpLYg4KSt4KWH4KSc4KS+ IHwg4KSw4KWHIOCkn+ClieCkruCksuCkv+CkguCkuOCkqCDgpKjgpYcg4KS54KWAIOCkuOCksOCl jeCkteCkquCljeCksOCkpeCkriBAIOCkmuCkv+CkqOCljeCkuSDgpJXgpL4g4KSa4KSv4KSoIOCk leCkv+Ckr+CkviDgpJTgpLAg4KSH4KSo4KWN4KS54KWAIOCkleCliyDgpIjgpK7gpYfgpLIg4KSV 4KS+IOCkhuCkteCkv+Ckt+CljeCkleCkvuCksOCklSDgpK7gpL7gpKjgpL4g4KSc4KS+4KSk4KS+ IOCkueCliAo=
注記

場合によっては、Amazon を使用して送信するメッセージContent-Transfer-Encodingで 8 ビットを使用できますSES。ただし、Amazon SESがメッセージに変更を加える必要がある場合 (例えば、オープンおよびクリックトラッキング を使用する場合)、受信者の受信トレイに到着すると、8 ビットエンコードされたコンテンツが正しく表示されないことがあります。このため、7 ビット ではないコンテンツは常にエンコードする必要がありますASCII。

添付ファイル

E メールにファイルをアタッチするには、base64 エンコードを使用して添付ファイルをエンコードする必要があります。アタッチメントは通常、以下のヘッダーを含む専用のMIMEメッセージパートに配置されます。

  • Content-Type – 添付ファイルの種類。一般的な MIME Content-Type 宣言の例を次に示します。

    • プレーンテキストファイルContent-Type: text/plain; name="sample.txt"

    • Microsoft Word ドキュメントContent-Type: application/msword; name="document.docx"

    • JPG イメージContent-Type: image/jpeg; name="photo.jpeg"

  • Content-Disposition – 受取人の E メールクライアントがコンテンツをどのように処理するかを指定します。添付ファイルの場合、この値は Content-Disposition: attachment です。

  • Content-Transfer-Encoding – 添付ファイルのエンコードに使用されるスキーム。添付ファイルでは、ほとんどの場合この値は base64 です。

  • エンコードされた添付ファイル例に示すように、実際の添付ファイルをエンコードして、添付ファイルヘッダーの下の本文に含める必要があります。

Amazon は、最も一般的なファイルタイプSESを受け入れます。Amazon が受け入れないファイルタイプのリストについては、SES「」を参照してくださいAmazon サポートSESされていないアタッチメントタイプ

Amazon v2 を使用した raw E SES API メールの送信

Amazon SESAPIv2 には SendEmailアクションが用意されています。これにより、コンテンツタイプをシンプル、raw、またはテンプレートのいずれかに設定するときに指定した形式で E メールメッセージを構成して送信できます。詳細な説明については、「」を参照してくださいSendEmail。次の例では、raw E メール形式を使用してメッセージを送信rawするコンテンツタイプを として指定します。

注記

SendEmail に複数の呼び出しを作成する場合の E メール送信速度向上方法については、「Amazon SES のスループットを上げる」を参照してください。

メッセージ本文には、正しくフォーマットされ、適切なヘッダーフィールドとメッセージ本文がエンコードされた raw E メールメッセージを含める必要があります。アプリケーション内で raw メッセージを手動で構成することはできますが、既存のメールライブラリを使用して構成するほうが、はるかに簡単です。

Java

次のコード例は、 JavaMailライブラリと の使用方法を示しています。 AWS SDK for Java raw E メールを作成して送信するには、 を使用します。

package com.amazonaws.samples; import java.io.ByteArrayOutputStream; import java.io.IOException; import java.io.PrintStream; import java.nio.ByteBuffer; import java.util.Properties; // JavaMail libraries. Download the JavaMail API // from https://javaee.github.io/javamail/ import javax.activation.DataHandler; import javax.activation.DataSource; import javax.activation.FileDataSource; import javax.mail.Message; import javax.mail.MessagingException; import javax.mail.Session; import javax.mail.internet.AddressException; import javax.mail.internet.InternetAddress; import javax.mail.internet.MimeBodyPart; import javax.mail.internet.MimeMessage; import javax.mail.internet.MimeMultipart; // AWS SDK libraries. Download the AWS SDK for Java // from https://aws.amazon.com/sdk-for-java import com.amazonaws.regions.Regions; import com.amazonaws.services.simpleemail.AmazonSimpleEmailService; import com.amazonaws.services.simpleemail.AmazonSimpleEmailServiceClientBuilder; import com.amazonaws.services.simpleemail.model.RawMessage; import com.amazonaws.services.simpleemail.model.SendRawEmailRequest; public class AmazonSESSample { // Replace sender@example.com with your "From" address. // This address must be verified with Amazon SES. private static String SENDER = "Sender Name <sender@example.com>"; // Replace recipient@example.com with a "To" address. If your account // is still in the sandbox, this address must be verified. private static String RECIPIENT = "recipient@example.com"; // Specify a configuration set. If you do not want to use a configuration // set, comment the following variable, and the // ConfigurationSetName=CONFIGURATION_SET argument below. private static String CONFIGURATION_SET = "ConfigSet"; // The subject line for the email. private static String SUBJECT = "Customer service contact info"; // The full path to the file that will be attached to the email. // If you're using Windows, escape backslashes as shown in this variable. private static String ATTACHMENT = "C:\\Users\\sender\\customers-to-contact.xlsx"; // The email body for recipients with non-HTML email clients. private static String BODY_TEXT = "Hello,\r\n" + "Please see the attached file for a list " + "of customers to contact."; // The HTML body of the email. private static String BODY_HTML = "<html>" + "<head></head>" + "<body>" + "<h1>Hello!</h1>" + "<p>Please see the attached file for a " + "list of customers to contact.</p>" + "</body>" + "</html>"; public static void main(String[] args) throws AddressException, MessagingException, IOException { Session session = Session.getDefaultInstance(new Properties()); // Create a new MimeMessage object. MimeMessage message = new MimeMessage(session); // Add subject, from and to lines. message.setSubject(SUBJECT, "UTF-8"); message.setFrom(new InternetAddress(SENDER)); message.setRecipients(Message.RecipientType.TO, InternetAddress.parse(RECIPIENT)); // Create a multipart/alternative child container. MimeMultipart msg_body = new MimeMultipart("alternative"); // Create a wrapper for the HTML and text parts. MimeBodyPart wrap = new MimeBodyPart(); // Define the text part. MimeBodyPart textPart = new MimeBodyPart(); textPart.setContent(BODY_TEXT, "text/plain; charset=UTF-8"); // Define the HTML part. MimeBodyPart htmlPart = new MimeBodyPart(); htmlPart.setContent(BODY_HTML,"text/html; charset=UTF-8"); // Add the text and HTML parts to the child container. msg_body.addBodyPart(textPart); msg_body.addBodyPart(htmlPart); // Add the child container to the wrapper object. wrap.setContent(msg_body); // Create a multipart/mixed parent container. MimeMultipart msg = new MimeMultipart("mixed"); // Add the parent container to the message. message.setContent(msg); // Add the multipart/alternative part to the message. msg.addBodyPart(wrap); // Define the attachment MimeBodyPart att = new MimeBodyPart(); DataSource fds = new FileDataSource(ATTACHMENT); att.setDataHandler(new DataHandler(fds)); att.setFileName(fds.getName()); // Add the attachment to the message. msg.addBodyPart(att); // Try to send the email. try { System.out.println("Attempting to send an email through Amazon SES " +"using the AWS SDK for Java..."); // Instantiate an Amazon SES client, which will make the service // call with the supplied AWS credentials. AmazonSimpleEmailService client = AmazonSimpleEmailServiceClientBuilder.standard() // Replace US_WEST_2 with the AWS Region you're using for // Amazon SES. .withRegion(Regions.US_WEST_2).build(); // Print the raw email content on the console PrintStream out = System.out; message.writeTo(out); // Send the email. ByteArrayOutputStream outputStream = new ByteArrayOutputStream(); message.writeTo(outputStream); RawMessage rawMessage = new RawMessage(ByteBuffer.wrap(outputStream.toByteArray())); SendRawEmailRequest rawEmailRequest = new SendRawEmailRequest(rawMessage) .withConfigurationSetName(CONFIGURATION_SET); client.sendRawEmail(rawEmailRequest); System.out.println("Email sent!"); // Display an error if something goes wrong. } catch (Exception ex) { System.out.println("Email Failed"); System.err.println("Error message: " + ex.getMessage()); ex.printStackTrace(); } } }
Python

次のコード例は、Python email.mime パッケージと AWS SDK for Python (Boto) raw E メールを作成して送信するには、 を使用します。

import json import boto3 from botocore.exceptions import ClientError from email.mime.multipart import MIMEMultipart from email.mime.text import MIMEText from email.mime.application import MIMEApplication import os def boto3_rawemailv2(): SENDER = "Sender <sender@example.com>" RECIPIENT = "recipient@example.com" CONFIGURATION_SET = "ConfigSet" AWS_REGION = "us-east-1" SUBJECT = "Customer service contact info" ATTACHMENT = "path/to/customers-to-contact.xlsx" BODY_TEXT = "Hello,\r\nPlease see the attached file for a list of customers to contact." # The HTML body of the email. BODY_HTML = """\ <html> <head/> <body> <h1>Hello!</h1> <p>Please see the attached file for a list of customers to contact.</p> </body> </html> """ # The character encoding for the email. CHARSET = "utf-8" msg = MIMEMultipart('mixed') # Add subject, from and to lines. msg['Subject'] = SUBJECT msg['From'] = SENDER msg['To'] = RECIPIENT # Create a multipart/alternative child container. msg_body = MIMEMultipart('alternative') # Encode the text and HTML content and set the character encoding. This step is # necessary if you're sending a message with characters outside the ASCII range. textpart = MIMEText(BODY_TEXT.encode(CHARSET), 'plain', CHARSET) htmlpart = MIMEText(BODY_HTML.encode(CHARSET), 'html', CHARSET) # Add the text and HTML parts to the child container. msg_body.attach(textpart) msg_body.attach(htmlpart) # Define the attachment part and encode it using MIMEApplication. att = MIMEApplication(open(ATTACHMENT, 'rb').read()) # Add a header to tell the email client to treat this part as an attachment, # and to give the attachment a name. att.add_header('Content-Disposition','attachment',filename=os.path.basename(ATTACHMENT)) # Attach the multipart/alternative child container to the multipart/mixed # parent container. msg.attach(msg_body) msg.attach(att) #changes start from here strmsg = str(msg) body = bytes (strmsg, 'utf-8') client = boto3.client('sesv2') response = client.send_email( FromEmailAddress=SENDER, Destination={ 'ToAddresses': [RECIPIENT] }, Content={ 'Raw': { 'Data': body } } ) print(response) boto3_rawemailv2 ()