Skip to content

Instantly share code, notes, and snippets.

@manugarri
Forked from lavr/send_email.py
Last active February 23, 2016 11:46
Show Gist options
  • Save manugarri/a39a6039190e528b6ba7 to your computer and use it in GitHub Desktop.
Save manugarri/a39a6039190e528b6ba7 to your computer and use it in GitHub Desktop.
# see also: http://code.activestate.com/recipes/578150-sending-non-ascii-emails-from-python-3/
import os
import smtplib
from email.utils import formataddr
from email.utils import formatdate
from email.utils import COMMASPACE
from email.header import Header
from email import encoders
from email.mime.multipart import MIMEMultipart
from email.mime.base import MIMEBase
from email.mime.text import MIMEText
from email.mime.image import MIMEImage
import Jinja2
sender_name, sender_email = "CI", "[email protected]"
recipient_addr = ['[email protected]']
j = jinja2.Environment()
ctx = {"project_name": "user/project1", "build_id": 121}
html = j.from_string("<html><p>Build passed: {{ project_name }} <img src='cid:icon.png'> ...").render(**ctx)
text = j.from_string("Build passed: {{ project_name }} ...").render(**ctx)
subject = j.from_string("Passed: {{ project_name }}#{{ build_id }}").render(**ctx)
attachments = ['icon.png']
sender_name = Header(mail_from, 'utf-8').encode()
msg_root = MIMEMultipart('mixed')
msg_root['Date'] = formatdate(localtime=1)
msg_root['From'] = formataddr((sender_name, sender_addr))
msg_root['To'] = COMMASPACE.join(recipient_addr)
msg_root['Subject'] = Header(subject, 'utf-8')
msg_root.preamble = 'This is a multi-part message in MIME format.'
msg_related = MIMEMultipart('related')
msg_root.attach(msg_related)
msg_alternative = MIMEMultipart('alternative')
msg_related.attach(msg_alternative)
msg_text = MIMEText(text.encode('utf-8'), 'plain', 'utf-8')
msg_alternative.attach(msg_text)
msg_html = MIMEText(html.encode('utf-8'), 'html', 'utf-8')
msg_alternative.attach(msg_html)
for i, img in enumerate(img_list):
with open(img, 'rb') as fp:
msg_image = MIMEImage(fp.read())
msg_image.add_header('Content-ID', '<image{}>'.format(i))
msg_related.attach(msg_image)
for attachment in attachments:
fname = os.path.basename(attachment)
with open(attachment, 'rb') as f:
msg_attach = MIMEBase('application', 'octet-stream')
msg_attach.set_payload(f.read())
encoders.encode_base64(msg_attach)
msg_attach.add_header('Content-Disposition', 'attachment',
filename=(Header(fname, 'utf-8').encode()))
msg_attach.add_header('Content-ID', '<%s>' % (Header(fname, 'utf-8').encode()))
msg_root.attach(msg_attach)
mail_server = smtplib.SMTP(smtp, port)
mail_server.ehlo()
try:
mail_server.starttls()
mail_server.ehlo()
except smtplib.SMTPException as e:
# message is not sent, retry later
print(e)
mail_server.login(login, password)
mail_server.send_message(msg_root)
mail_server.quit()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment