Skip to content

Instantly share code, notes, and snippets.

@maxking
Last active Aug 29, 2015
Embed
What would you like to do?
#!/usr/bin/env python3
import smtplib
from email.mime.text import MIMEText
from email.mime.multipart import MIMEMultipart
from email.headerregistry import Address
# Create the base text message.
msg = MIMEMultipart('related')
msg['Subject'] = "Ayons asperges pour le déjeuner"
msg['From'] = Address("Pepé Le Pew", "pepe@example.com")
msg['To'] = (Address("Penelope Pussycat", "penelope@example.com"),
Address("Fabrette Pussycat", "fabrette@example.com"))
# You must first add attachments and then the main html part
# so that they can be related using the cid generated.
with open("roasted-asparagus.jpg", 'rb') as img:
cid = msg.add_related(img.read(), 'image', 'jpeg')
html = """\
<html>
<head></head>
<body>
<p>Salut!<\p>
<p>Cela ressemble à un excellent
<a href="http://www.yummly.com/recipe/Roasted-Asparagus-Epicurious-203718>
recipie
</a> déjeuner.
</p>
<img src="cid:{}" \>
</body>
</html>
""".format(cid)
msg.add_related(html, 'html')
# note that we needed to peel the <> off the msgid for use in the html.
# Make a local copy of what we are going to send.
with open('outgoing.msg', 'wb') as f:
f.write(bytes(msg))
# Send the message via local SMTP server.
with smtplib.SMTP('localhost') as s:
s.send_message(msg)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment