I am using AWS lambda to send email with attachments through Amazon SES. The attachment files stored in S3 bucket. Has anyone had any experience using lambda and sending emails via ses, through a lambda function?
here is my code:
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)
found this error:
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'>