【问题标题】:Use AWS Lambda and SES to send an email使用 AWS Lambda 和 SES 发送电子邮件
【发布时间】:2022-01-20 15:09:16
【问题描述】:

我运行了以下脚本,该脚本在我的计算机上运行,​​但在 AWS Lambda 中不起作用。我所做的只是添加了“def lambda_handler(event, context): return event”函数作为 lambda 所需的函数。我运行了几次 Lambda 测试。 我没有收到 SES 电子邮件,并且在 Lambda 中执行它时也没有错误。知道为什么吗?

import boto3
from botocore.exceptions import ClientError


SENDER = "Sender Name <testu@test.com>"
RECIPIENT = "test@test.com"
CONFIGURATION_SET = "ConfigSet"
AWS_REGION = "ap-southeast-2"
SUBJECT = "Amazon SES Test (SDK for Python)"
BODY_TEXT = ("Amazon SES Test (Python)\r\n"
             "This email was sent with Amazon SES using the "
             "AWS SDK for Python (Boto)."
            )
            

BODY_HTML = """<html>
</html>
            """            
def lambda_handler(event, context):
    return event
    
# The character encoding for the email.
CHARSET = "UTF-8"

# Create a new SES resource and specify a region.
client = boto3.client('ses',region_name=AWS_REGION)

try:
    response = client.send_email(
        Destination={
            'ToAddresses': [
                RECIPIENT,
            ],
        },
        Message={
            'Body': {
                'Html': {
                    'Charset': CHARSET,
                    'Data': BODY_HTML,
                },
                'Text': {
                    'Charset': CHARSET,
                    'Data': BODY_TEXT,
                },
            },
            'Subject': {
                'Charset': CHARSET,
                'Data': SUBJECT,
            },
        },
        Source=SENDER,
        ConfigurationSetName=CONFIGURATION_SET,
    )

except ClientError as e:
    print(e.response['Error']['Message'])
else:
    print(response['MessageId'])

【问题讨论】:

  • 你需要在lambda_handler函数里面执行你想运行的代码

标签: python aws-lambda


【解决方案1】:

正如 Anon Coward 所说,您必须在处理函数内部执行 SES 发送,并将 return 语句放在该函数的底部。

它应该看起来像这样:

def lambda_handler(event, context):
    response = client.send_email(PAYLOAD_HERE_)

    return {
        "statusCode": 200,
        "headers": {
            "Content-Type": "application/json"
        },
        "body": json.dumps({
            "Region ": json_region
        })
    }

【讨论】:

    猜你喜欢
    • 2019-12-13
    • 2016-11-17
    • 1970-01-01
    • 1970-01-01
    • 2020-11-25
    • 1970-01-01
    • 2018-03-31
    • 2011-08-07
    • 2020-10-20
    相关资源
    最近更新 更多