Total Pageviews

2024/02/07

如何透過 AWS Lambda 呼叫 SES (Simple Email Service) 發信

實作步驟如下

1. 建立 Verified Identities來做為測試用途的 Sender 與 Receiver email address


2. 建立 Lambda Function 後,進入 Configuration => Permission,確認該 Role 具備 SES 角色權限


3. 呼叫 SES 的 Python code

import boto3
from botocore.exceptions import ClientError

def lambda_handler(event, context):
    # 建立 SES 客戶端
    ses_client = boto3.client('ses', region_name='us-east-1')  # 請根據需要替換為您的 SES 區域

    # 電子郵件參數
    SENDER = "hekarey795@giratex.com"  # 替換為您的發件人地址
    RECIPIENT = "hekarey795@giratex.com"  # 替換為您的收件人地址
    SUBJECT = "AWS SES Test Email from Lambda"
    BODY_TEXT = ("This is a test email sent from AWS Lambda using SES")
    CHARSET = "UTF-8"

    # 嘗試發送電子郵件
    try:
        response = ses_client.send_email(
            Destination={
                'ToAddresses': [
                    RECIPIENT,
                ],
            },
            Message={
                'Body': {
                    'Text': {
                        'Charset': CHARSET,
                        'Data': BODY_TEXT,
                    },
                },
                'Subject': {
                    'Charset': CHARSET,
                    'Data': SUBJECT,
                },
            },
            Source=SENDER,
        )
    except ClientError as e:
        print(e.response['Error']['Message'])
    else:
        print("Email sent! Message ID:"),
        print(response['MessageId'])

4. 執行結果


5. 檢查信箱






No comments: