

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

# Amazon SES API v2 を使用した raw E メールの送信
<a name="send-email-raw"></a>

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

## E メールヘッダーフィールドについて
<a name="send-email-raw-headers"></a>

Simple Mail Transfer Protocol (SMTP) は、E メールエンベロープとそのパラメータのいくつかを定義することにより、E メールメッセージの送信方法を定義しますが、メッセージの内容については何も定義しません。一方、Internet Message Format（[RFC 5322](https://www.ietf.org/rfc/rfc5322.txt)）は、メッセージの構成方法を定義します。

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

## Raw E メール MIME メッセージ構造の使用
<a name="send-email-raw-mime"></a>

SMTP プロトコルはもともと 7 ビット ASCII 文字のみを含む E メールメッセージを送信するように設計されていました。この仕様により、ASCII 以外のテキストエンコード (Unicode など)、バイナリコンテンツ、または添付ファイルでは SMTP が不十分になります。多目的インターネットメール拡張‎ (MIME) 標準は、SMTP を使用して、他の多くの種類のコンテンツを送信できるようにするために開発されたものです。

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

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

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

```
 1. From: "Sender Name" <sender@example.com>
 2. To: recipient@example.com
 3. Subject: Customer service contact info
 4. Content-Type: multipart/mixed;
 5.     boundary="a3f166a86b56ff6c37755292d690675717ea3cd9de81228ec2b76ed4a15d6d1a"
 6. 
 7. --a3f166a86b56ff6c37755292d690675717ea3cd9de81228ec2b76ed4a15d6d1a
 8. Content-Type: multipart/alternative;
 9.     boundary="sub_a3f166a86b56ff6c37755292d690675717ea3cd9de81228ec2b76ed4a15d6d1a"
10. 
11. --sub_a3f166a86b56ff6c37755292d690675717ea3cd9de81228ec2b76ed4a15d6d1a
12. Content-Type: text/plain; charset=iso-8859-1
13. Content-Transfer-Encoding: quoted-printable
14. 
15. Please see the attached file for a list of customers to contact.
16. 
17. --sub_a3f166a86b56ff6c37755292d690675717ea3cd9de81228ec2b76ed4a15d6d1a
18. Content-Type: text/html; charset=iso-8859-1
19. Content-Transfer-Encoding: quoted-printable
20. 
21. <html>
22. <head></head>
23. <body>
24. <h1>Hello!</h1>
25. <p>Please see the attached file for a list of customers to contact.</p>
26. </body>
27. </html>
28. 
29. --sub_a3f166a86b56ff6c37755292d690675717ea3cd9de81228ec2b76ed4a15d6d1a--
30. 
31. --a3f166a86b56ff6c37755292d690675717ea3cd9de81228ec2b76ed4a15d6d1a
32. Content-Type: text/plain; name="customers.txt"
33. Content-Description: customers.txt
34. Content-Disposition: attachment;filename="customers.txt";
35.     creation-date="Sat, 05 Aug 2017 19:35:36 GMT";
36. Content-Transfer-Encoding: base64
37. 
38. SUQsRmlyc3ROYW1lLExhc3ROYW1lLENvdW50cnkKMzQ4LEpvaG4sU3RpbGVzLENhbmFkYQo5MjM4
39. OSxKaWUsTGl1LENoaW5hCjczNCxTaGlybGV5LFJvZHJpZ3VleixVbml0ZWQgU3RhdGVzCjI4OTMs
40. QW5heWEsSXllbmdhcixJbmRpYQ==
41. 
42. --a3f166a86b56ff6c37755292d690675717ea3cd9de81228ec2b76ed4a15d6d1a--
```

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

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

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

この例のように MIME パートを他のパートに入れ子にすると、入れ子になったパートは、親のパートの `boundary` パラメータとは異なる `boundary` パラメータを使用する必要があります。これらの境界は固有の文字列でなければなりません。MIME パーツ間の境界を定義するには、2 つのハイフンを (--) タイプし、その後に境界文字列が続きます。MIME パーツの最後に、境界文字列の先頭および末尾の両方に 2 つのハイフンを置きます。

**注記**  
メッセージに 500 MIME を超えるパーツを含めることはできません。

### MIME エンコード
<a name="send-email-mime-encoding"></a>

古いシステムとの互換性を維持するために、Amazon SES は [RFC 2821](https://tools.ietf.org/html/rfc2821) で定義されている SMTP の 7 ビット ASCII 制限を優先します。非 ASCII 文字を含むコンテンツを送信する場合は、これらの文字を 7 ビット ASCII 文字を使用する形式にエンコードする必要があります。

#### E メールアドレス
<a name="send-email-mime-encoding-addresses"></a>

E メールアドレスは、7 ビット ASCII 文字列になっている必要があります。送信先または送信元の E メールアドレス内で、ドメインの部分に Unicode 文字が含まれる場合は、Punycode を使用してドメインをエンコードする必要があります。Punycode は E メールアドレスのローカル部分 (@ 記号の前の部分) では許可されていません。また、「差出人」名にも許可されていません。「差出人」名に Unicode 文字を使用する場合は、このセクションに説明されているように、MIME encoded-word 構文を使用して「差出人」名をエンコードする必要があります。Punycode の詳細については、[RFC 3492](http://tools.ietf.org/html/rfc3492) を参照してください。

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

#### E メールヘッダー
<a name="send-email-mime-encoding-headers"></a>

メッセージヘッダーをエンコードするには、MIME encoded-word 構文を使用します。MIME encoded word 構文では、次の形式が使用されます。

```
=?{{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](https://tools.ietf.org/html/rfc2047) を参照してください。base64 エンコードの詳細については、[RFC 2045](https://tools.ietf.org/html/rfc2045) を参照してください。

#### メッセージ本文
<a name="send-email-mime-encoding-body"></a>

メッセージの本文をエンコードするには、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 SES を使用して送信するメッセージに 8 ビットの`Content-Transfer-Encoding`を使用できます。ただし、Amazon SES がメッセージを変更する必要がある場合 (たとえば、[オープンとクリックの追跡](faqs-metrics.md)を使用した場合)、8 ビットでエンコードされたコンテンツは、受取人の受信トレイに届いたときに正しく表示されないことがあります。このため、7 ビットの ASCII 以外のコンテンツは常にエンコードする必要があります。

#### 添付ファイル
<a name="send-email-mime-encoding-files"></a>

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` です。
+ **エンコードされた添付ファイル** – [例に示すように](#send-email-raw-mime)、実際の添付ファイルをエンコードして、添付ファイルヘッダーの下の本文に含める必要があります。

Amazon SES は最も一般的なファイルタイプに対応しています。Amazon SES が対応していないファイルの種類の一覧については、「[SES でサポート対象外の添付ファイルのタイプ](attachments.md#mime-types)」を参照してください。

## Amazon SES API v2 を使用した raw E メールの送信
<a name="send-email-raw-api"></a>

Amazon SES API v2 は `SendEmail` アクションを提供します。これにより、コンテンツタイプを simple、raw、または templated のいずれかを指定し、このように指定した形式の E メールメッセージを作成して送信できるようになります。詳細については、「[https://docs.aws.amazon.com/ses/latest/APIReference-V2/API_SendEmail.html](https://docs.aws.amazon.com/ses/latest/APIReference-V2/API_SendEmail.html)」を参照してください。次の例では、コンテンツ タイプを `raw` として指定して、raw E メール形式を使用してメッセージを送信します。

**注記**  
`SendEmail` に複数の呼び出しを作成する場合の E メール送信速度向上方法については、「[Amazon SES のスループットを上げる](troubleshoot-throughput-problems.md)」を参照してください。

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

------
#### [ Java ]

次のコード例は、[JavaMail](https://javaee.github.io/javamail/)ライブラリと[AWS SDK for Java](https://aws.amazon.com/sdk-for-java)を使用して raw E メールを作成および送信する方法を示しています。

```
  1. package com.amazonaws.samples;
  2. 
  3. import java.io.ByteArrayOutputStream;
  4. import java.io.IOException;
  5. import java.io.PrintStream;
  6. import java.nio.ByteBuffer;
  7. import java.util.Properties;
  8. 
  9. // JavaMail libraries. Download the JavaMail API 
 10. // from https://javaee.github.io/javamail/
 11. import javax.activation.DataHandler;
 12. import javax.activation.DataSource;
 13. import javax.activation.FileDataSource;
 14. import javax.mail.Message;
 15. import javax.mail.MessagingException;
 16. import javax.mail.Session;
 17. import javax.mail.internet.AddressException;
 18. import javax.mail.internet.InternetAddress;
 19. import javax.mail.internet.MimeBodyPart;
 20. import javax.mail.internet.MimeMessage;
 21. import javax.mail.internet.MimeMultipart;
 22. 
 23. // AWS SDK libraries. Download the AWS SDK for Java // from https://aws.amazon.com/sdk-for-java
 24. import com.amazonaws.regions.Regions;
 25. import com.amazonaws.services.simpleemail.AmazonSimpleEmailService;
 26. import com.amazonaws.services.simpleemail.AmazonSimpleEmailServiceClientBuilder;
 27. import com.amazonaws.services.simpleemail.model.RawMessage;
 28. import com.amazonaws.services.simpleemail.model.SendRawEmailRequest;
 29. 
 30. public class AmazonSESSample {
 31. 
 32. 	// Replace sender@example.com with your "From" address.
 33. 	// This address must be verified with Amazon SES.
 34. 	private static String SENDER = "{{Sender Name}} <{{sender@example.com}}>";
 35. 
 36. 	// Replace recipient@example.com with a "To" address. If your account 
 37. 	// is still in the sandbox, this address must be verified.
 38. 	private static String RECIPIENT = "{{recipient@example.com}}";
 39. 
 40. 	// Specify a configuration set. If you do not want to use a configuration
 41. 	// set, comment the following variable, and the 
 42. 	// ConfigurationSetName=CONFIGURATION_SET argument below.
 43. 	private static String CONFIGURATION_SET = "{{ConfigSet}}";
 44. 
 45. 	// The subject line for the email.
 46. 	private static String SUBJECT = "Customer service contact info";
 47. 
 48. 	// The full path to the file that will be attached to the email.
 49. 	// If you're using Windows, escape backslashes as shown in this variable.
 50. 	private static String ATTACHMENT = "C:\\Users\\sender\\customers-to-contact.xlsx";
 51. 
 52. 	// The email body for recipients with non-HTML email clients.
 53. 	private static String BODY_TEXT = "Hello,\r\n"
 54.                                         + "Please see the attached file for a list "
 55.                                         + "of customers to contact.";
 56. 
 57. 	// The HTML body of the email.
 58. 	private static String BODY_HTML = "<html>"
 59.                                         + "<head></head>"
 60.                                         + "<body>"
 61.                                         + "<h1>Hello!</h1>"
 62.                                         + "<p>Please see the attached file for a "
 63.                                         + "list of customers to contact.</p>"
 64.                                         + "</body>"
 65.                                         + "</html>";
 66. 
 67.     public static void main(String[] args) throws AddressException, MessagingException, IOException {
 68.             	
 69.     	Session session = Session.getDefaultInstance(new Properties());
 70.         
 71.         // Create a new MimeMessage object.
 72.         MimeMessage message = new MimeMessage(session);
 73.         
 74.         // Add subject, from and to lines.
 75.         message.setSubject(SUBJECT, "UTF-8");
 76.         message.setFrom(new InternetAddress(SENDER));
 77.         message.setRecipients(Message.RecipientType.TO, InternetAddress.parse(RECIPIENT));
 78. 
 79.         // Create a multipart/alternative child container.
 80.         MimeMultipart msg_body = new MimeMultipart("alternative");
 81.         
 82.         // Create a wrapper for the HTML and text parts.        
 83.         MimeBodyPart wrap = new MimeBodyPart();
 84.         
 85.         // Define the text part.
 86.         MimeBodyPart textPart = new MimeBodyPart();
 87.         textPart.setContent(BODY_TEXT, "text/plain; charset=UTF-8");
 88.                 
 89.         // Define the HTML part.
 90.         MimeBodyPart htmlPart = new MimeBodyPart();
 91.         htmlPart.setContent(BODY_HTML,"text/html; charset=UTF-8");
 92.                 
 93.         // Add the text and HTML parts to the child container.
 94.         msg_body.addBodyPart(textPart);
 95.         msg_body.addBodyPart(htmlPart);
 96.         
 97.         // Add the child container to the wrapper object.
 98.         wrap.setContent(msg_body);
 99.         
100.         // Create a multipart/mixed parent container.
101.         MimeMultipart msg = new MimeMultipart("mixed");
102.         
103.         // Add the parent container to the message.
104.         message.setContent(msg);
105.         
106.         // Add the multipart/alternative part to the message.
107.         msg.addBodyPart(wrap);
108.         
109.         // Define the attachment
110.         MimeBodyPart att = new MimeBodyPart();
111.         DataSource fds = new FileDataSource(ATTACHMENT);
112.         att.setDataHandler(new DataHandler(fds));
113.         att.setFileName(fds.getName());
114.         
115.         // Add the attachment to the message.
116.         msg.addBodyPart(att);
117. 
118.         // Try to send the email.
119.         try {
120.             System.out.println("Attempting to send an email through Amazon SES "
121.                               +"using the AWS SDK for Java...");
122. 
123.             // Instantiate an Amazon SES client, which will make the service 
124.             // call with the supplied AWS credentials.
125.             AmazonSimpleEmailService client = 
126.                     AmazonSimpleEmailServiceClientBuilder.standard()
127.                     // Replace US_WEST_2 with the AWS Region you're using for
128.                     // Amazon SES.
129.                     .withRegion(Regions.US_WEST_2).build();
130.             
131.             // Print the raw email content on the console
132.             PrintStream out = System.out;
133.             message.writeTo(out);
134. 
135.             // Send the email.
136.             ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
137.             message.writeTo(outputStream);
138.             RawMessage rawMessage = 
139.             		new RawMessage(ByteBuffer.wrap(outputStream.toByteArray()));
140. 
141.             SendRawEmailRequest rawEmailRequest = 
142.             		new SendRawEmailRequest(rawMessage)
143.             		    .withConfigurationSetName(CONFIGURATION_SET);
144.             
145.             client.sendRawEmail(rawEmailRequest);
146.             System.out.println("Email sent!");
147.         // Display an error if something goes wrong.
148.         } catch (Exception ex) {
149.           System.out.println("Email Failed");
150.             System.err.println("Error message: " + ex.getMessage());
151.             ex.printStackTrace();
152.         }
153.     }
154. }
```

------
#### [ Python ]

次のコード例は、[Python email.mime](https://docs.python.org/3.8/library/email.mime.html) パッケージと [AWS SDK for Python (Boto)](https://aws.amazon.com/sdk-for-python) を使用して raw E メールを作成および送信する方法を示しています。

```
 1. import json
 2. import boto3
 3. from botocore.exceptions import ClientError
 4. from email.mime.multipart import MIMEMultipart
 5. from email.mime.text import MIMEText
 6. from email.mime.application import MIMEApplication
 7. import os
 8. 
 9. def boto3_rawemailv2():
10.     SENDER = "Sender <sender@example.com>"
11.     RECIPIENT = "recipient@example.com"
12.     CONFIGURATION_SET = "ConfigSet"
13.     AWS_REGION = "us-east-1"
14.     SUBJECT = "Customer service contact info"
15.     ATTACHMENT = "path/to/customers-to-contact.xlsx"
16.     BODY_TEXT = "Hello,\r\nPlease see the attached file for a list of customers to contact."
17. 
18.     # The HTML body of the email.
19.     BODY_HTML = """\
20.     <html>
21.     <head/>
22.     <body>
23.     <h1>Hello!</h1>
24.     <p>Please see the attached file for a list of customers to contact.</p>
25.     </body>
26.     </html>
27.     """
28. 
29.     # The character encoding for the email.
30.     CHARSET = "utf-8"
31.     msg = MIMEMultipart('mixed')
32.     # Add subject, from and to lines.
33.     msg['Subject'] = SUBJECT 
34.     msg['From'] = SENDER 
35.     msg['To'] = RECIPIENT
36.     
37.     # Create a multipart/alternative child container.
38.     msg_body = MIMEMultipart('alternative')
39.     
40.     # Encode the text and HTML content and set the character encoding. This step is
41.     # necessary if you're sending a message with characters outside the ASCII range.
42.     textpart = MIMEText(BODY_TEXT.encode(CHARSET), 'plain', CHARSET)
43.     htmlpart = MIMEText(BODY_HTML.encode(CHARSET), 'html', CHARSET)
44.     
45.     # Add the text and HTML parts to the child container.
46.     msg_body.attach(textpart)
47.     msg_body.attach(htmlpart)
48.     
49.     # Define the attachment part and encode it using MIMEApplication.
50.     att = MIMEApplication(open(ATTACHMENT, 'rb').read())
51.     
52.     # Add a header to tell the email client to treat this part as an attachment,
53.     # and to give the attachment a name.
54.     att.add_header('Content-Disposition','attachment',filename=os.path.basename(ATTACHMENT))
55.     
56.     # Attach the multipart/alternative child container to the multipart/mixed
57.     # parent container.
58.     msg.attach(msg_body)
59.     msg.attach(att)
60. 
61.     #changes start from here
62.     strmsg = str(msg)
63.     body = bytes (strmsg, 'utf-8')
64. 
65. 
66. 
67.     
68.     client = boto3.client('sesv2')
69.     response = client.send_email(
70.     FromEmailAddress=SENDER,
71.     Destination={
72.         'ToAddresses': [RECIPIENT]
73.     },
74.     Content={
75.         'Raw': {
76.             'Data': body
77.         }
78.     }
79.     )
80.     print(response)
81. boto3_rawemailv2 ()
```

------