English

AWS EmulatorのSESでテンプレートメールを送る方法

​​AWS Emulator​Amazon SES,Amazon SNS,Amazon SQS,AWS CLI

Amazon SES のメールテンプレートは、AWS Emulator を使うと、AWS のアカウントなしで手元で作って送れます。会員登録の確認メールや注文確認メールのように、宛先ごとに名前や注文番号を差し込むメールを、ローカル環境の開発やテストで確かめたいときの手順です。テンプレートの作り方、送る前に展開した形を確かめる方法、値が足りないときに何が起きるか、宛先ごとに値を変える一括送信を、検証環境で実行したコマンドと出力で示します。

補足

検証環境は Ubuntu 24.04(x86_64)、AWS Emulator 1.0.624(2026年11月26日リリース)、AWS CLI 2.42.4、Python 3.11 です。AWS のアカウントと認証情報は使っていないので、本物の SES での動き、メールが実際に届くか、料金は確かめていません。本物の SES に触れるところは、公式ドキュメントを出どころにしています。リクエストの中に件名と本文を直接書くインラインテンプレート、AWS SDK からの送信、HTML の本文がメールソフトでどう見えるかは試していません。古い API(aws ses)での送信は、この記事では扱いません。

準備:エミュレーターを起動して、送信元と宛先を登録する

AWS Emulator の入れ方は、別の記事「AWS EmulatorをUbuntuに入れて使い始める方法」で扱っています。検証環境では、Linux 向けの手順にある Debian パッケージを、gpg で署名を確かめてから入れました。起動の -t off は、既定で AWS に送られる利用状況のデータ(テレメトリー)を止める指定です。

text
$ aws-emulator -t off

別の端末で、公式ドキュメントにある環境変数を設定し、AWS CLI の接続先をエミュレーターに向けます。

bash
export AWS_ENDPOINT_URL=https://127.0.0.1:9297
export AWS_SHARED_CREDENTIALS_FILE=~/.aws/emulator/9297/emulator_credentials
export AWS_CONFIG_FILE=~/.aws/emulator/9297/config
export AWS_CA_BUNDLE=~/.aws/emulator/9297/ca.pem
export AWS_EC2_METADATA_DISABLED=true
export AWS_DISABLE_HOST_PREFIX_INJECTION=true
export AWS_REGION=us-east-1
export AWS_DEFAULT_REGION=us-east-1
unset AWS_ACCESS_KEY_ID AWS_SECRET_ACCESS_KEY AWS_SESSION_TOKEN AWS_PROFILE

SES で送るには、送信元のアドレスを ID として登録し、確認を済ませておく必要があります。エミュレーターでは、確認のメールのリンクを開かなくても、待っていると SUCCESS になりました(5つのアドレスがすべて SUCCESS になるまで4秒でした)。この流れと、テンプレートを使わない送信は、別の記事「AWS EmulatorでSESのメール送信を試す方法」で詳しく扱っています。この記事では、送信元の sender@example.com と、宛先の a@example.com から d@example.com までを登録しました。

text
$ aws sesv2 create-email-identity --email-identity sender@example.com --query IdentityType --output text
EMAIL_ADDRESS
(a@example.com〜d@example.com も同じように作成)
$ s=$(date +%s); for a in sender@example.com a@example.com b@example.com c@example.com d@example.com; do for i in $(seq 30); do st=$(aws sesv2 get-email-identity --email-identity $a --query VerificationStatus --output text); [ "$st" = SUCCESS ] && break; sleep 1; done; echo "$a $st"; done; echo "$(( $(date +%s) - s ))秒"
sender@example.com SUCCESS
a@example.com SUCCESS
b@example.com SUCCESS
c@example.com SUCCESS
d@example.com SUCCESS
4秒

テンプレートを作る

テンプレートには、件名(Subject)、テキストの本文(Text)、HTML の本文(Html)を書きます。公式ドキュメントのテンプレートの説明のとおり、値を差し込む場所は {{name}} のように書きます。今回は、名前とプランを差し込む登録完了メールにしました。

text
$ cat welcome.json
{"Subject":"{{name}}さん、ようこそ","Text":"{{name}}さん、{{plan}}プランへの登録ありがとうございます。","Html":"<p>{{name}}さん、<b>{{plan}}</b>プランへの登録ありがとうございます。</p>"}

create-email-template で作ると、成功しても何も表示されません。保存された中身は get-email-template で読めます。同じ名前でもう一度作ると、AlreadyExistsException になりました(中身を変えるときは、後の節の update-email-template を使います)。

text
$ aws sesv2 create-email-template --template-name welcome --template-content file://welcome.json
$ aws sesv2 create-email-template --template-name welcome --template-content file://welcome.json

aws: [ERROR]: An error occurred (AlreadyExistsException) when calling the CreateEmailTemplate operation: Template welcome already exists for account id <12桁のアカウントID>

送る前に、展開した形を確かめる

test-render-email-template に差し込む値を JSON で渡すと、TestRenderEmailTemplate の API リファレンスの説明どおり、送られるメールの形(MIME のメッセージ)が返ります。メールを送らずに、テンプレートと値の組み合わせを確かめられます。

text
$ aws sesv2 test-render-email-template --template-name welcome --template-data '{"name":"ねこ","plan":"無料"}' --query RenderedTemplate --output text
Subject: =?UTF-8?B?44Gt44GT44GV44KT44CB44KI44GG44GT44Gd?=
MIME-Version: 1.0
Content-Type: multipart/alternative; boundary="----=_Part_d2071097-ee30-4ec4-9f27-4840cfb41980"

------=_Part_d2071097-ee30-4ec4-9f27-4840cfb41980
Content-Type: text/plain; charset=UTF-8
Content-Transfer-Encoding: quoted-printable

=E3=81=AD=E3=81=93=E3=81=95=E3=82=93=E3=80=81=E7=84=A1=E6=96=99=E3=83=97=E3=
(以下略)

テキストと HTML の両方を書いたので、2つの本文をまとめた multipart/alternative の形になっています。日本語は、件名が Base64、本文が quoted-printable という形に変換されていて、このままでは読めません。Python の標準ライブラリの email で読み直す、短いスクリプトを用意しました。

python
# decode.py:標準入力の MIME メッセージを読み、件名と各パートを復号して表示する
import sys, email
from email import policy
m = email.message_from_string(sys.stdin.read(), policy=policy.default)
print("Subject:", m["Subject"])
for p in m.walk():
    if p.is_multipart(): continue
    print("---", p.get_content_type())
    print(p.get_content().rstrip("\n"))

出力をこのスクリプトに渡すと、件名と2つの本文に、名前とプランが差し込まれているのが分かります。

text
$ aws sesv2 test-render-email-template --template-name welcome --template-data '{"name":"ねこ","plan":"無料"}' --query RenderedTemplate --output text | python3 decode.py
Subject: ねこさん、ようこそ
--- text/plain
ねこさん、無料プランへの登録ありがとうございます。
--- text/html
<p>ねこさん、<b>無料</b>プランへの登録ありがとうございます。</p>

差し込む値に <b> や & を入れると、HTML の本文にもそのまま入りました。公式ドキュメントの高度な差し込みの説明にも、SES は HTML のテンプレートを展開するときに特殊文字を置き換えない(エスケープしない)と書かれています。問い合わせフォームの入力のように、利用者が入力した文字を差し込むときは、送る側のプログラムで先にエスケープしておく必要があります。

text
$ aws sesv2 test-render-email-template --template-name welcome --template-data '{"name":"<b>ねこ</b>","plan":"A&B"}' --query RenderedTemplate --output text | python3 decode.py
Subject: <b>ねこ</b>さん、ようこそ
--- text/plain
<b>ねこ</b>さん、A&Bプランへの登録ありがとうございます。
--- text/html
<p><b>ねこ</b>さん、<b>A&B</b>プランへの登録ありがとうございます。</p>

テンプレートを使って送る

send-email の --content に Template を書き、テンプレートの名前と、差し込む値を渡します。値は JSON そのものではなく、JSON を文字列にしたものを渡すので、中の " を \" にします。成功すると MessageId が返ります(MessageId の中のハイフンに挟まれた12桁の数字は、<12桁の連番> に置き換えています)。

text
$ aws sesv2 send-email --from-email-address sender@example.com --destination ToAddresses=a@example.com --content '{"Template":{"TemplateName":"welcome","TemplateData":"{\"name\":\"ねこ\",\"plan\":\"無料\"}"}}'
{
    "MessageId": "010001a216a9e8c9-2d613b7b-53c9-e0b8-4c0b-<12桁の連番>-000000"
}

テンプレートの名前を間違えたときと、値の JSON が壊れているときは、その場でエラーになりました。

text
$ aws sesv2 send-email --from-email-address sender@example.com --destination ToAddresses=a@example.com --content '{"Template":{"TemplateName":"nope","TemplateData":"{}"}}'

aws: [ERROR]: An error occurred (NotFoundException) when calling the SendEmail operation: Template nope does not exist.
$ aws sesv2 send-email --from-email-address sender@example.com --destination ToAddresses=a@example.com --content '{"Template":{"TemplateName":"welcome","TemplateData":"{\"name\":}"}}'

aws: [ERROR]: An error occurred (BadRequestException) when calling the SendEmail operation: Template rendering data is invalid

値が足りないと、送信は成功してもあとで Rendering Failure になる

差し込む値が1つ足りないときは、test-render-email-template と send-email で結果が分かれました。test-render-email-template では、どの値が足りないかを示すエラーになります。

text
$ aws sesv2 test-render-email-template --template-name welcome --template-data '{"name":"ねこ"}'

aws: [ERROR]: An error occurred (BadRequestException) when calling the TestRenderEmailTemplate operation: Attribute 'plan' is not present in the rendering data.

一方、同じ値で send-email を呼ぶと、エラーにならず MessageId が返りました。公式ドキュメントのテンプレートの説明には、差し込みの内容が正しくないメールは、SES が受け付けても届けられないことがあると書かれています。そのため同じページでは、送信イベントの1つである「Rendering Failure」を、設定セット(configuration set)で受け取るよう勧めています。

イベントを受け取る準備(SNS と SQS)

設定セットには、イベントの送り先を登録します。検証環境では、SNS のトピックと、それを購読する SQS のキューを作りました。ARN とキューの URL の中のアカウントIDは <12桁のアカウントID> に置き換えているので、試すときは create-topic と create-queue の出力に出た値を使ってください。

text
$ aws sns create-topic --name ses-events --query TopicArn --output text
arn:aws:sns:us-east-1:<12桁のアカウントID>:ses-events
$ aws sqs create-queue --queue-name ses-events --query QueueUrl --output text
https://127.0.0.1:9297/<12桁のアカウントID>/ses-events

このあとのコマンドで使うため、トピックの ARN を $T に、キューの URL を $Q に、キューの ARN を $QA に入れておきます。キューの ARN は get-queue-attributes で読みます。同じ名前で create-topic と create-queue をもう一度呼ぶと、さきほどと同じトピックとキューが返りました。

text
$ T=$(aws sns create-topic --name ses-events --query TopicArn --output text)
$ Q=$(aws sqs create-queue --queue-name ses-events --query QueueUrl --output text)
$ QA=$(aws sqs get-queue-attributes --queue-url $Q --attribute-names QueueArn --query Attributes.QueueArn --output text)

キューには、このトピックからの送信を許すポリシーを付けます。ポリシーは JSON を文字列にして Policy 属性に入れる必要があるので、Python で attrs.json を作ってから set-queue-attributes に渡しました。

text
$ python3 - "$T" "$QA" > attrs.json <<'PY'
import json, sys
t, q = sys.argv[1], sys.argv[2]
pol = {"Version":"2012-10-17","Statement":[{"Effect":"Allow","Principal":{"Service":"sns.amazonaws.com"},"Action":"sqs:SendMessage","Resource":q,"Condition":{"ArnEquals":{"aws:SourceArn":t}}}]}
print(json.dumps({"Policy": json.dumps(pol)}))
PY
$ aws sqs set-queue-attributes --queue-url $Q --attributes file://attrs.json

購読では RawMessageDelivery=true を付けます。SNS の公式ドキュメントの説明のとおり、SNS のメタデータが取り除かれ、SES のイベントの JSON がそのままキューに入ります(出力の末尾の購読IDは <購読ID> に置き換えています)。続けて設定セットを作り、SEND と RENDERING_FAILURE の2種類のイベントをトピックに送るように登録しました。

text
$ aws sns subscribe --topic-arn $T --protocol sqs --notification-endpoint $QA --attributes RawMessageDelivery=true --query SubscriptionArn --output text
arn:aws:sns:us-east-1:<12桁のアカウントID>:ses-events:<購読ID>
$ aws sesv2 create-configuration-set --configuration-set-name tpl-test
$ aws sesv2 create-configuration-set-event-destination --configuration-set-name tpl-test --event-destination-name to-sns --event-destination '{"Enabled":true,"MatchingEventTypes":["SEND","RENDERING_FAILURE"],"SnsDestination":{"TopicArn":"arn:aws:sns:us-east-1:<12桁のアカウントID>:ses-events"}}'

キューに届いたイベントは、次のスクリプト(events.sh)で受け取ります。イベントを1件ずつ、種類、宛先、MessageId、件名、エラーメッセージの順に1行で表示し、受け取ったメッセージはキューから消します。

bash
#!/bin/bash
# SQS のキューに届いたイベントをすべて受け取り、1件を1行で表示してから、受け取ったメッセージを消す。
# 2つ目の引数に full を付けると、Rendering Failure のイベントは JSON の全体を表示する。
Q="$1"; MODE="$2"
while :; do
  out=$(aws sqs receive-message --queue-url "$Q" --max-number-of-messages 10 --wait-time-seconds 3 --output json)
  [ -z "$out" ] && break
  echo "$out" | MODE="$MODE" python3 -c '
import sys, json, os
for m in json.load(sys.stdin)["Messages"]:
    e = json.loads(m["Body"])
    if os.environ["MODE"] == "full" and e["eventType"] == "Rendering Failure":
        print(json.dumps(e, ensure_ascii=False, indent=2)); continue
    subject = e["mail"]["commonHeaders"].get("subject", "(件名なし)")
    error = e.get("failure", {}).get("errorMessage", "")
    print(e["eventType"], e["mail"]["destination"][0], e["mail"]["messageId"], subject, error)
'
  echo "$out" | python3 -c 'import sys, json; [print(m["ReceiptHandle"]) for m in json.load(sys.stdin)["Messages"]]' |
    while read -r h; do aws sqs delete-message --queue-url "$Q" --receipt-handle "$h"; done
done

値が足りない送信で届くイベント

--configuration-set-name tpl-test を付けて、値がそろった送信と、plan が足りない送信を1通ずつ送りました。

text
$ aws sesv2 send-email --from-email-address sender@example.com --destination ToAddresses=a@example.com --configuration-set-name tpl-test --content '{"Template":{"TemplateName":"welcome","TemplateData":"{\"name\":\"ねこ\",\"plan\":\"無料\"}"}}'
{
    "MessageId": "010001a216aa0d33-f400a844-2307-cf26-5760-<12桁の連番>-000000"
}
$ aws sesv2 send-email --from-email-address sender@example.com --destination ToAddresses=a@example.com --configuration-set-name tpl-test --content '{"Template":{"TemplateName":"welcome","TemplateData":"{\"name\":\"ねこ\"}"}}'
{
    "MessageId": "010001a216aa1059-714bfc4b-4549-d065-6d1c-<12桁の連番>-000000"
}

値がそろった1通目は、件名の入った Send だけでした。値が足りない2通目は、件名のない Send のあとに Rendering Failure が届き、足りない値の名前がエラーメッセージに入っていました。

text
$ bash events.sh $Q
Send a@example.com 010001a216aa0d33-f400a844-2307-cf26-5760-<12桁の連番>-000000 ねこさん、ようこそ
Send a@example.com 010001a216aa1059-714bfc4b-4549-d065-6d1c-<12桁の連番>-000000 (件名なし)
Rendering Failure a@example.com 010001a216aa1059-714bfc4b-4549-d065-6d1c-<12桁の連番>-000000 (件名なし) Attribute 'plan' is not present in the rendering data.

エミュレーターでは、値の不足は send-email の結果からは分からず、このイベントで初めて分かりました。続けて、b@example.com 宛てに、値を何も渡さない(TemplateData を "{}" にする)送信もしました。

text
$ aws sesv2 send-email --from-email-address sender@example.com --destination ToAddresses=b@example.com --configuration-set-name tpl-test --content '{"Template":{"TemplateName":"welcome","TemplateData":"{}"}}'
{
    "MessageId": "010001a216aa39a7-2354f821-c477-8353-b377-<12桁の連番>-000000"
}

bash events.sh $Q full で、Rendering Failure のイベントの JSON の全体を表示しました。次のブロックは、その末尾の failure の部分だけを抜き出したものです。公式ドキュメントのイベントの中身の説明と同じく、templateName と errorMessage の2つが入っていました。

text
  "failure": {
    "templateName": "welcome",
    "errorMessage": "Attribute 'name' is not present in the rendering data."
  }

宛先ごとに値を変えて、まとめて送る

send-bulk-email を使うと、1回の呼び出しで、宛先ごとに違う値を差し込んで送れます。公式ドキュメントによると、本物の SES で1回に指定できる宛先(Destination)は50個までです。--default-content に既定の値を書き、宛先ごとの値は ReplacementTemplateData に書きます。今回は、次の4通りの宛先を並べました。

text
$ cat bulk.json
[
  {"Destination":{"ToAddresses":["a@example.com"]},
   "ReplacementEmailContent":{"ReplacementTemplate":{"ReplacementTemplateData":"{\"name\":\"たま\",\"plan\":\"有料\"}"}}},
  {"Destination":{"ToAddresses":["b@example.com"]},
   "ReplacementEmailContent":{"ReplacementTemplate":{"ReplacementTemplateData":"{}"}}},
  {"Destination":{"ToAddresses":["c@example.com"]}},
  {"Destination":{"ToAddresses":["d@example.com"]},
   "ReplacementEmailContent":{"ReplacementTemplate":{"ReplacementTemplateData":"{\"name\":"}}}
]

a@example.com にはその宛先用の値を、b@example.com には空の {} を渡し、c@example.com には宛先ごとの値を書いていません。d@example.com の値は、わざと壊れた JSON にしています。

text
$ aws sesv2 send-bulk-email --from-email-address sender@example.com --default-content '{"Template":{"TemplateName":"welcome","TemplateData":"{\"name\":\"お客\",\"plan\":\"無料\"}"}}' --configuration-set-name tpl-test --bulk-email-entries file://bulk.json
{
    "BulkEmailEntryResults": [
        {
            "Status": "SUCCESS",
            "MessageId": "010001a216aa5f14-1117797b-cc8a-7641-3c19-<12桁の連番>-000000"
        },
        {
            "Status": "SUCCESS",
            "MessageId": "010001a216aa5f14-c23130e0-df11-4567-c4b6-<12桁の連番>-000000"
        },
        {
            "Status": "SUCCESS",
            "MessageId": "010001a216aa5f14-614773c9-d604-29ca-ed4e-<12桁の連番>-000000"
        },
        {
            "Status": "INVALID_PARAMETER",
            "Error": "Template rendering data is invalid"
        }
    ]
}

エミュレーターでは、結果は宛先ごとに、並べた順で返りました。壊れた JSON の宛先だけが INVALID_PARAMETER になり、ほかの3通は受け付けられました。キューに届いたイベントを、さきほどの events.sh で見ます。

text
$ bash events.sh $Q
Send b@example.com 010001a216aa5f14-c23130e0-df11-4567-c4b6-<12桁の連番>-000000 (件名なし)
Send a@example.com 010001a216aa5f14-1117797b-cc8a-7641-3c19-<12桁の連番>-000000 たまさん、ようこそ
Rendering Failure b@example.com 010001a216aa5f14-c23130e0-df11-4567-c4b6-<12桁の連番>-000000 (件名なし) Attribute 'name' is not present in the rendering data.
Send c@example.com 010001a216aa5f14-614773c9-d604-29ca-ed4e-<12桁の連番>-000000 お客さん、ようこそ

件名を見ると、a@example.com には宛先ごとに書いた値が、宛先ごとの値を書かなかった c@example.com には既定の値が差し込まれました。気を付けたいのは b@example.com です。公式ドキュメントのテンプレートの説明では、ReplacementTemplateData が空の {} なら、既定の値(DefaultContent の TemplateData)が使われると書かれています。エミュレーターでは既定の値は使われず、値がないものとして Rendering Failure になりました。

エミュレーターの公開されているソースコードの一括送信の処理(send_bulk_email.rs)も、既定の値を使うのは ReplacementTemplateData を書かなかったときだけ、という作りでした(読んだのは、入れた 1.0.624 とは別の、リポジトリの最新のコミットです)。エミュレーターで既定の値を使わせたいときは、c@example.com のように、宛先ごとの値そのものを書かないようにします。

each や if を使うテンプレートは、エミュレーターでは送れない

公式ドキュメントの高度な差し込みの説明によると、保存したテンプレートでは Handlebars という書き方が使え、{{order.id}} のような入れ子の値、{{#each}} での繰り返し、{{#if}} での条件分岐、インラインのパーシャルを書けます。注文の品物を並べ、クーポンがあるときだけ1行足すテンプレートを作りました。

text
$ cat order.json
{"Subject":"ご注文番号 {{order.id}}","Text":"{{#each order.items}}- {{this}}\n{{/each}}{{#if coupon}}クーポン {{coupon}} を使いました。{{/if}}"}

test-render-email-template では、品物が1行ずつ並び、クーポンがないときはその行が出ませんでした。

text
$ aws sesv2 test-render-email-template --template-name order --template-data '{"order":{"id":"A-1001","items":["かつおぶし","ねこじゃらし"]},"coupon":"NEKO10"}' --query RenderedTemplate --output text | python3 decode.py
Subject: ご注文番号 A-1001
--- text/plain
- かつおぶし
- ねこじゃらし
クーポン NEKO10 を使いました。
$ aws sesv2 test-render-email-template --template-name order --template-data '{"order":{"id":"A-1002","items":["かつおぶし"]}}' --query RenderedTemplate --output text | python3 decode.py
Subject: ご注文番号 A-1002
--- text/plain
- かつおぶし

ところが、このテンプレートで send-email や send-bulk-email を呼ぶと、NotImplemented で断られました。セクション({{#each}} や {{#if}})、パーシャル、ヘルパーを使うテンプレートでの送信は、エミュレーターには実装されていない、という意味のエラーです。

text
$ aws sesv2 send-email --from-email-address sender@example.com --destination ToAddresses=a@example.com --content '{"Template":{"TemplateName":"order","TemplateData":"{\"order\":{\"id\":\"A-1001\",\"items\":[\"かつおぶし\"]}}"}}'

aws: [ERROR]: An error occurred (NotImplemented) when calling the SendEmail operation: operation SendEmail with a template that uses a section, a partial or a helper call is scaffolded but not implemented in this emulator

エミュレーターで送信まで試せるのは、{{name}} のように値を差し込むだけのテンプレートです。

テンプレートを書き換える・消す

update-email-template で、中身を丸ごと置き換えられます。今回は、HTML の本文をなくし、件名の語順を変えました。

text
$ aws sesv2 update-email-template --template-name welcome --template-content '{"Subject":"ようこそ、{{name}}さん","Text":"{{name}}さん、登録ありがとうございます。"}'
$ aws sesv2 get-email-template --template-name welcome --query TemplateContent
{
    "Subject": "ようこそ、{{name}}さん",
    "Text": "{{name}}さん、登録ありがとうございます。"
}

使わなくなったテンプレートは delete-email-template で消します。消したあとに get-email-template で読むと、NotFoundException になりました。

text
$ aws sesv2 delete-email-template --template-name order
$ aws sesv2 get-email-template --template-name order

aws: [ERROR]: An error occurred (NotFoundException) when calling the GetEmailTemplate operation: Template order does not exist.

エミュレーターでテンプレートを確かめるときは、差し込んだ結果を test-render-email-template で見て、送信の結果を、MessageId と、設定セットで受け取る Send や Rendering Failure のイベントで見る、という分け方になります。

​Posted by 86