Skip to content

Instantly share code, notes, and snippets.

@jordanst3wart
Last active August 5, 2018 04:51
Show Gist options
  • Save jordanst3wart/0d11cbc007cb1d65d52ce6771e1f926e to your computer and use it in GitHub Desktop.
Save jordanst3wart/0d11cbc007cb1d65d52ce6771e1f926e to your computer and use it in GitHub Desktop.
import boto3
from email.mime.text import MIMEText
from email.mime.image import MIMEImage
from email.mime.multipart import MIMEMultipart
from email.mime.application import MIMEApplication
from botocore.exceptions import ClientError
def send_message(from_email, to_emails, subject, images=[], attachments=[]):
body_html = html_template()
msg = create_msg(from_email, to_emails, subject, body_html, images, attachments)
send_raw_email(msg, to_emails)
# implicitly knows about images as cid:img-$filename
def html_template():
return """
<html>
<head></head>
<body>
<h1>WoW!!</h1>
Some image:
<img src='cid:img-output.png'>
<p>This email was sent with:
<a href='https://aws.amazon.com/ses/'>Amazon SES</a> using the
<a href='https://aws.amazon.com/sdk-for-python/'>
AWS SDK for Python (Boto)</a>.</p>
</body>
</html>
"""
# outputs MIME TYPE, and html
def msg_image(filename, path):
mime_img = MIMEImage(open(path, 'rb').read())
mime_img.add_header('Content-ID', '<img-' + filename + '>')
return mime_img
# outputs MIME TYPE
def msg_attachment(filename, path):
attachment = MIMEApplication(open(path, 'rb').read())
attachment.add_header('Content-Disposition', 'attachment', filename=filename)
return attachment
def create_msg(from_email, to_emails, subject, body_html, images, attachments):
CHARSET = "utf-8"
msg = MIMEMultipart('mixed')
msg['Subject'] = subject
msg['From'] = from_email
msg['To'] = ", ".join(to_emails)
msg_body = MIMEMultipart('alternative')
body = MIMEText(body_html.encode(CHARSET), 'html', CHARSET)
body_text = MIMEText("Use a html supported mail client...".encode(CHARSET), 'plain', CHARSET)
for image in images:
mime_img = msg_image(image['filename'], image['path'])
msg.attach(mime_img)
# actually needs to be in this order... (text then html)
msg_body.attach(body_text)
msg_body.attach(body)
for attachment in attachments:
msg.attach(msg_attachment(attachment['filename'], attachment['path']))
msg.attach(msg_body)
return msg
def send_raw_email(msg, to_emails):
session = boto3.Session(profile_name='us') # use US profile configured in ~/.aws as ses only available in a few regions
client = session.client('ses')
try:
response = client.send_raw_email(
Source=msg['FROM'],
Destinations=to_emails,
RawMessage={'Data': msg.as_string()})
except ClientError as e:
print(e.response['Error']['Message'])
else:
print("Email sent! Message ID:"),
print(response['MessageId'])
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment