LoginSignup
0
0

More than 3 years have passed since last update.

SES で受信したメールを AWS Lambda で gmail に転送する Ruby スクリプト

Last updated at Posted at 2019-08-20

下記記事を参考にしたが、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"
  1. bundle install --path vendor/bundle
  2. zip -r function.zip lambda_function.rb vendor
  3. aws lambda update-function-code --function-name lambdaのfunction名 --zip-file fileb://function.zip
0
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0