我正在使用AWS lambda通过Amazon SES发送带附件的电子邮件。附件文件存储在S3存储桶中。有没有人有过使用lambda和通过ses发送电子邮件的经验,通过lambda函数?
这是我的代码:
import boto3
from email.mime.text import MIMEText
from email.mime.application import MIMEApplication
from email.mime.multipart import MIMEMultipart
ses = boto3.client('ses')
s3_client = boto3.client('s3')
to_emails = ["xxx", "xxx"]
COMMASPACE = ', '
def lambda_handler(event, context):
# create raw email
msg = MIMEMultipart()
msg['Subject'] = 'Email subject'
msg['From'] = 'xxx'
msg['To'] = COMMASPACE.join(to_emails) ## joined the array of email strings
# edit: didn't end up using this ^
part = MIMEText('Attached is an important CSV')
msg.attach(part)
file_name = s3_client.download_file('x_file', 'x.jpg', '/tmp/x.jpg')
if file_name:
part = MIMEApplication(open(file_name, "rb").read())
part.add_header('Content-Disposition', 'attachment', filename=file_name)
msg.attach(part)
ses.send_raw_email(RawMessage=msg.as_string(), Source=msg['From'], Destinations=to_emails)
发现了这个错误:
Parameter validation failed:
Invalid type for parameter RawMessage, value: Content-Type: multipart/mixed; boundary="===============1951926695068149774=="
MIME-Version: 1.0
Subject: Email subject
From: xxx
To: xxx, xxx
--===============1951926695068149774==
Content-Type: text/plain; charset="us-ascii"
MIME-Version: 1.0
Content-Transfer-Encoding: 7bit
Attached is an important CSV
--===============1951926695068149774==--
, type: <type 'str'>, valid types: <type 'dict'>: ParamValidationError
Traceback (most recent call last):
File "/var/task/lambda_function.py", line 33, in lambda_handler
ses.send_raw_email(RawMessage=msg.as_string(), Source=msg['From'], Destinations=to_emails)
File "/var/runtime/botocore/client.py", line 278, in _api_call
return self._make_api_call(operation_name, kwargs)
File "/var/runtime/botocore/client.py", line 548, in _make_api_call
api_params, operation_model, context=request_context)
File "/var/runtime/botocore/client.py", line 601, in _convert_to_request_dict
api_params, operation_model)
File "/var/runtime/botocore/validate.py", line 270, in serialize_to_request
raise ParamValidationError(report=report.generate_report())
ParamValidationError: Parameter validation failed:
Invalid type for parameter RawMessage, value: Content-Type: multipart/mixed; boundary="===============1951926695068149774=="
MIME-Version: 1.0
Subject: Email subject
From: xxx
To:xxx, xxx
--===============1951926695068149774==
Content-Type: text/plain; charset="us-ascii"
MIME-Version: 1.0
Content-Transfer-Encoding: 7bit
Attached is an important CSV
--===============1951926695068149774==--
, type: <type 'str'>, valid types: <type 'dict'>
答案 0 :(得分:2)
要解决此问题,您应该使用:
ses.send_raw_email(RawMessage={
'Data': msg.as_string(),
},
Source=msg['From'],
Destinations=to_emails
)
中所述