3
0

導入

こんにちは。エンジニアのYamaです。

特殊なパターンですが、Amazon Simple Email Service (SES)で受信したメールをLambdaで一括処理することがあったので、備忘録的に残しておきます。

実装内容

今回作成したLambdaは、CloudWatch Eventsで毎日23時に実行することを想定しています。
SESの取得範囲は、前日の23時から当日の23時までのものになります。
また、SESから取得したデータの加工に関しては、割愛しています。

Lambdaソース

import boto3
from datetime import datetime, timedelta

def lambda_handler(event, context):
    # SES クライアント
    ses_client = boto3.client('ses', region_name='your-region')

    # 今日の日付を取得
    today = datetime.utcnow().date()
    end_time = datetime(today.year, today.month, today.day, 23, 0, 0)
    # 24時間前
    start_time = end_time - timedelta(hours=24)

    # SESの受信メールを一括取得する
    response = ses_client.list_receipt_rules(
        StartDate=start_time,
        EndDate=end_time
    )

    for receipt_rule in response['ReceiptRules']:
        ### 取得したメール情報を処理する ###
        print(receipt_rule)

    # 任意の処理が完了した後、レスポンス
    return {
        'statusCode': 200,
        'body': 'Get received mail info: success'
    }

最後に

案外実装は簡単でした。
SESはメール送信に利用するユースケースが多いと思うので、あまり使う機会はないかもしれませんが、もし受信メールに対してLambdaで処理を行いたい際はご参考にしていただけると幸いです。

3
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
3
0