AWS Lambda中使用SES Python发送带附件邮件超时问题求助
解决Lambda中使用SES Python发送带附件邮件超时的问题
我看了你的代码和问题描述,这里有几个明显的问题会导致Lambda超时或者执行异常,咱们一步步来解决:
1. 修复重复的邮件组装代码
你在try-except块之后重复写了组装邮件附件和添加到消息的代码,这不仅是冗余,还会导致邮件内容被重复处理,甚至可能引发不可预期的错误。另外,最后一行代码里的ATTACHMENT变量根本没定义,这会抛出NameError(虽然你的错误是超时,但这个问题必须先修复)。
2. 修复后的完整代码
import boto3 from botocore.exceptions import ClientError import os from email.mime.multipart import MIMEMultipart from email.mime.text import MIMEText from email.mime.application import MIMEApplication def send_mail_with_attach_ses(sender, recipient, aws_region, subject, file_name): # The email body for recipients with non-HTML email clients. BODY_TEXT = "Hello,\r\nPlease find the attached file." # The HTML body of the email. BODY_HTML = """\ <html> <head></head> <body> <h1>Hello!</h1> <p>Please find the attached file.</p> </body> </html> """ CHARSET = "utf-8" client = boto3.client('ses', region_name=aws_region) msg = MIMEMultipart('mixed') # Add subject, from and to lines. msg['Subject'] = subject msg['From'] = sender msg['To'] = recipient # Create multipart/alternative child container for text and HTML parts msg_body = MIMEMultipart('alternative') textpart = MIMEText(BODY_TEXT.encode(CHARSET), 'plain', CHARSET) htmlpart = MIMEText(BODY_HTML.encode(CHARSET), 'html', CHARSET) msg_body.attach(textpart) msg_body.attach(htmlpart) # Check if file exists before proceeding if not os.path.exists(file_name): print(f"Error: File {file_name} does not exist") return print(f"File {file_name} exists, proceeding to attach") # Define the attachment part with open(file_name, 'rb') as f: att = MIMEApplication(f.read()) att.add_header('Content-Disposition', 'attachment', filename=os.path.basename(file_name)) # Attach the body and attachment to the parent message msg.attach(msg_body) msg.attach(att) try: response = client.send_raw_email( Source=msg['From'], Destinations=[recipient], RawMessage={ 'Data': msg.as_string(), }, # 如果你不确定ConfigurationSet是否存在,可以先注释掉这一行测试 # ConfigurationSetName="ConfigSet" ) print(f"Email sent! Message ID: {response['MessageId']}") except ClientError as e: print(f"Error sending email: {e.response['Error']['Message']}") except Exception as e: print(f"Unexpected error: {str(e)}")
3. 排查Lambda超时的关键因素
如果修复代码后仍然超时,需要检查以下几点:
- Lambda执行角色权限:确保你的Lambda执行角色拥有
ses:SendRawEmail的权限,并且策略中允许发送到指定的收件人地址。可以在IAM控制台中查看角色的权限策略,添加类似下面的语句:{ "Effect": "Allow", "Action": "ses:SendRawEmail", "Resource": "*" } - SES沙箱模式限制:如果你的AWS账号还在SES沙箱模式下,发件人和收件人都必须是在SES控制台中验证过的邮箱地址。未验证的地址会导致邮件发送失败,部分情况下会引发请求超时。
- ConfigurationSet存在性:如果你保留了
ConfigurationSetName参数,确保这个配置集在指定的AWS区域中确实存在。不存在的配置集会导致请求失败,甚至超时。 - VPC配置(如果使用):如果你的Lambda函数配置了VPC,需要确保VPC有访问SES服务的权限。可以通过配置NAT网关或者VPC端点来允许Lambda访问SES。
- 文件大小限制:Lambda的/tmp目录最大可以存储512MB的文件,但SES有邮件大小限制(默认是10MB)。如果你的附件超过10MB,会导致发送失败,可能引发超时。
内容的提问来源于stack exchange,提问作者LG555
相关产品推荐
相关产品推荐

