AWS Lambda 到 Amazon SES 超时

问题描述 投票:0回答:1

下面用于发送 Amazon SES 电子邮件的代码运行良好。但是,我需要代码与本地 EC2 数据库通信,因此我需要将此 Lambda 函数添加到我的 VPC 和子网 - 此时,下面的代码停止工作并超时。

我该如何解决这个问题?

import json
import boto3

def send_email_ses(email):
    client = boto3.client('ses', region_name='eu-west-1')
    
    try:
        response = client.send_email(
            Destination={
                'ToAddresses': [email]
            },
            Message={
                'Body': {
                    'Text': {
                        'Charset': 'UTF-8',
                        'Data': 'Hello world',
                    }
                },
                'Subject': {
                    'Charset': 'UTF-8',
                    'Data': 'Welcome! Your API Key',
                },
            },
            Source='[email protected]'
        )
        return response['MessageId']
    except Exception as e:
        print(f"An error occurred: {str(e)}")
        return None

def lambda_handler(event, context):
    email = "[email protected]"
    message_id = send_email_ses(email)
    
    if message_id:
        body = f"Email Sent Successfully. MessageId is: {message_id}"
        status_code = 200
    else:
        body = "Failed to send email."
        status_code = 500

    return {
        'statusCode': status_code,
        'body': json.dumps(body)
    }`

错误信息:

Response { "errorMessage": "2024-06-26T05:12:37.998Z 34457ba1-910f-4f54-9ced-234dac1c0950 Task timed out after 5.01 seconds" }

如果我删除 VPC,它会再次运行。

python amazon-web-services aws-lambda amazon-vpc amazon-ses
1个回答
0
投票

当 AWS Lambda 函数连接到 VPC 时,默认情况下它没有 Internet 访问权限。因此,API 调用挂起。

最好的方法是在您的 VPC 中为 SES 创建 VPC 终端节点。这将提供对 Amazon SES 终端节点的直接访问,而无需通过 Internet。

请参阅:使用 Amazon SES 设置 VPC 终端节点 - Amazon Simple Email Service

或者,您可以将 Lambda 函数放置在私有子网中,并在公有子网中启动 NAT 网关。但是,NAT 网关需要收费,因此 VPC 终端节点是更便宜、更简单的选择。

© www.soinside.com 2019 - 2024. All rights reserved.