Thursday, November 10, 2016

Simple Email Service (SES) Sample Application

I could not find a simple example to send email using SES in Python. Turns out it is really easy. If you have a MIME formatted message you can simply call send_raw_message.

client = boto3.client("ses")
client.send_raw_email(RawMessage = {'Data': mime_formatted_message})

Of course the tricky part is the MIME formatting. Turns out that is really easy in Python. Here is a simple example.

message = MIMEText("Testing 123\nTesting 123\nTesting 123")
message['From'] = "sender@domain.com"
message['To'] = ["recipient1@domain.com", "recipient2@domain.com"]
message['Date'] = formatdate(localtime=True)
message['Subject'] = "Testing"

Then you can simply call as_string() and pass it to SES.

client = boto3.client("ses")
response = client.send_raw_email(RawMessage = {'Data': message.as_string()})

I messed around for a little while and created a few helper functions to handle HTML formatting and attachments. You can find the complete code in GitHub. I hope that helps someone.

No comments:

Post a Comment