下記記事を参考にしたが、Python
だったのでRuby
で書き直した。
SESのリージョンはus-east-1
を利用。
require 'aws-sdk'
require 'mail'
AWS_ACCESS_KEY_ID = "あなたの AWS_ACCESS_KEY_ID"
AWS_SECRET_ACCESS_KEY = "あなたの AWS_SECRET_ACCESS_KEY"
BUCKET_NAME = "mail が保存されている s3 のバケット名"
TO_ADDRESSES = ["mail@example.com"] # 送信したいメールアドレスの配列
SOURCE = "info@example.com" # 送信元メールアドレス
def aws_config_update(region)
Aws.config.update({
region: region,
credentials: Aws::Credentials.new(AWS_ACCESS_KEY_ID, AWS_SECRET_ACCESS_KEY)
})
end
def send_mail(ses, subject, body)
ses.send_email(
{
destination: {
to_addresses: TO_ADDRESSES
},
message: {
subject: {
charset: "UTF-8",
data: subject,
},
body: {
text: {
charset: "UTF-8",
data: body,
}
},
},
source: SOURCE
}
)
end
def lambda_handler(event:, context:)
aws_config_update("ap-northeast-1")
key = event["Records"][0]["s3"]["object"]["key"]
s3 = Aws::S3::Client.new
body = s3.get_object(bucket: BUCKET_NAME, key: key).body.string
mail = Mail.new(body)
aws_config_update("us-east-1")
ses = Aws::SES::Client.new
send_mail(ses, mail.subject, mail.decoded)
rescue => e
aws_config_update("us-east-1")
ses = Aws::SES::Client.new
send_mail(ses, "メール送信エラー", e.message)
end
mail gem
が必要なので、zip
で固めてアップロードする。
# Gemfile
source "https://rubygems.org"
git_source(:github) {|repo_name| "https://github.com/#{repo_name}" }
gem "mail"
bundle install --path vendor/bundle
zip -r function.zip lambda_function.rb vendor
aws lambda update-function-code --function-name lambdaのfunction名 --zip-file fileb://function.zip