Python: AWS Lambdaでメールを送信する

「AWS Lambda」->「関数の作成」->「一から作成」で関数を作成する。

import boto3

def send_email(source, to, subject, body):
    client = boto3.client('ses')
    response = client.send_email(
    Destination={
	'ToAddresses': [
            to
	],
    },
    Message={
	'Body': {
            'Text': {
		'Charset': 'UTF-8',
		'Data': body,
            },
	},
        'Subject': {
            'Charset': 'UTF-8',
            'Data': subject,
	},
    },
    Source=source
    )
    return response

def lambda_handler(event, context):
    source = '[メールアドレス]'
    to = '[メールアドレス]'
    subject = 'TEST'
    body = 'TEST\nTEST'
    r = send_email(source, to, subject, body)
    return r

IAMロールの設定を正しく行っていないと、以下のようなエラーが出力される。

{
  "errorMessage": "An error occurred (AccessDenied) when calling the SendEmail operation: User `XXXXXXXX’ is not authorized to perform `ses:SendEmail' on resource `XXXXXXXX’”,
  "errorType": "ClientError",
  "stackTrace": [
    [
      "/var/task/lambda_function.py",
      32,
      "lambda_handler",
      "r = send_email(source, to, subject, body)"
    ],
    [
      "/var/task/lambda_function.py",
      23,
      "send_email",
      "Source=source"
    ],
    [
      "/var/runtime/botocore/client.py",
      314,
      "_api_call",
      "return self._make_api_call(operation_name, kwargs)"
    ],
    [
      "/var/runtime/botocore/client.py",
      612,
      "_make_api_call",
      "raise error_class(parsed_response, operation_name)"
    ]
  ]
}

IAMロールにAmazonSESFullAccessポリシーをアタッチすることで解決。

コメントする

メールアドレスが公開されることはありません。 * が付いている欄は必須項目です