blob: 2e142b1e3b71e4b0e42386fa2b67ea0bd52cf64e [file] [log] [blame]
Benjamin Peterson90f5ba52010-03-11 22:53:45 +00001#!/usr/bin/env python3
Christian Heimes292d3512008-02-03 16:51:08 +00002
3import smtplib
4
R David Murray29d1bc02016-09-07 21:15:59 -04005from email.message import EmailMessage
6from email.headerregistry import Address
7from email.utils import make_msgid
Christian Heimes292d3512008-02-03 16:51:08 +00008
R David Murray29d1bc02016-09-07 21:15:59 -04009# Create the base text message.
10msg = EmailMessage()
11msg['Subject'] = "Ayons asperges pour le déjeuner"
12msg['From'] = Address("Pepé Le Pew", "pepe", "example.com")
13msg['To'] = (Address("Penelope Pussycat", "penelope", "example.com"),
14 Address("Fabrette Pussycat", "fabrette", "example.com"))
15msg.set_content("""\
16Salut!
Christian Heimes292d3512008-02-03 16:51:08 +000017
R David Murray29d1bc02016-09-07 21:15:59 -040018Cela ressemble à un excellent recipie[1] déjeuner.
Christian Heimes292d3512008-02-03 16:51:08 +000019
R David Murray29d1bc02016-09-07 21:15:59 -040020[1] http://www.yummly.com/recipe/Roasted-Asparagus-Epicurious-203718
21
22--Pepé
23""")
24
25# Add the html version. This converts the message into a multipart/alternative
26# container, with the original text message as the first part and the new html
27# message as the second part.
28asparagus_cid = make_msgid()
29msg.add_alternative("""\
Christian Heimes292d3512008-02-03 16:51:08 +000030<html>
31 <head></head>
32 <body>
R David Murray1ba3e6d2016-09-07 21:48:21 -040033 <p>Salut!</p>
R David Murray29d1bc02016-09-07 21:15:59 -040034 <p>Cela ressemble à un excellent
35 <a href="http://www.yummly.com/recipe/Roasted-Asparagus-Epicurious-203718>
36 recipie
37 </a> déjeuner.
Christian Heimes292d3512008-02-03 16:51:08 +000038 </p>
R David Murray1ba3e6d2016-09-07 21:48:21 -040039 <img src="cid:{asparagus_cid}" />
Christian Heimes292d3512008-02-03 16:51:08 +000040 </body>
41</html>
R David Murray29d1bc02016-09-07 21:15:59 -040042""".format(asparagus_cid=asparagus_cid[1:-1]), subtype='html')
43# note that we needed to peel the <> off the msgid for use in the html.
Christian Heimes292d3512008-02-03 16:51:08 +000044
R David Murray29d1bc02016-09-07 21:15:59 -040045# Now add the related image to the html part.
46with open("roasted-asparagus.jpg", 'rb') as img:
47 msg.get_payload()[1].add_related(img.read(), 'image', 'jpeg',
48 cid=asparagus_cid)
Christian Heimes292d3512008-02-03 16:51:08 +000049
R David Murray29d1bc02016-09-07 21:15:59 -040050# Make a local copy of what we are going to send.
51with open('outgoing.msg', 'wb') as f:
52 f.write(bytes(msg))
Christian Heimes292d3512008-02-03 16:51:08 +000053
54# Send the message via local SMTP server.
R David Murray29d1bc02016-09-07 21:15:59 -040055with smtplib.SMTP('localhost') as s:
56 s.send_message(msg)