email-alternative.py 1.68 KB
Newer Older
1
#!/usr/bin/env python3
Christian Heimes's avatar
Christian Heimes committed
2 3 4

import smtplib

5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29
from email.message import EmailMessage
from email.headerregistry import Address
from email.utils import make_msgid

# Create the base text message.
msg = EmailMessage()
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"))
msg.set_content("""\
Salut!

Cela ressemble à un excellent recipie[1] déjeuner.

[1] http://www.yummly.com/recipe/Roasted-Asparagus-Epicurious-203718

--Pepé
""")

# Add the html version.  This converts the message into a multipart/alternative
# container, with the original text message as the first part and the new html
# message as the second part.
asparagus_cid = make_msgid()
msg.add_alternative("""\
Christian Heimes's avatar
Christian Heimes committed
30 31 32
<html>
  <head></head>
  <body>
33
    <p>Salut!</p>
34
    <p>Cela ressemble à un excellent
35
        <a href="http://www.yummly.com/recipe/Roasted-Asparagus-Epicurious-203718">
36 37
            recipie
        </a> déjeuner.
Christian Heimes's avatar
Christian Heimes committed
38
    </p>
39
    <img src="cid:{asparagus_cid}" />
Christian Heimes's avatar
Christian Heimes committed
40 41
  </body>
</html>
42 43
""".format(asparagus_cid=asparagus_cid[1:-1]), subtype='html')
# note that we needed to peel the <> off the msgid for use in the html.
Christian Heimes's avatar
Christian Heimes committed
44

45 46 47 48
# Now add the related image to the html part.
with open("roasted-asparagus.jpg", 'rb') as img:
    msg.get_payload()[1].add_related(img.read(), 'image', 'jpeg',
                                     cid=asparagus_cid)
Christian Heimes's avatar
Christian Heimes committed
49

50 51 52
# Make a local copy of what we are going to send.
with open('outgoing.msg', 'wb') as f:
    f.write(bytes(msg))
Christian Heimes's avatar
Christian Heimes committed
53 54

# Send the message via local SMTP server.
55 56
with smtplib.SMTP('localhost') as s:
    s.send_message(msg)