• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1#!/usr/bin/env python3
2
3import smtplib
4
5from email.message import EmailMessage
6from email.headerregistry import Address
7from email.utils import make_msgid
8
9# 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!
17
18Cela ressemble à un excellent recipie[1] déjeuner.
19
20[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("""\
30<html>
31  <head></head>
32  <body>
33    <p>Salut!</p>
34    <p>Cela ressemble à un excellent
35        <a href="http://www.yummly.com/recipe/Roasted-Asparagus-Epicurious-203718">
36            recipie
37        </a> déjeuner.
38    </p>
39    <img src="cid:{asparagus_cid}" />
40  </body>
41</html>
42""".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.
44
45# 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)
49
50# Make a local copy of what we are going to send.
51with open('outgoing.msg', 'wb') as f:
52    f.write(bytes(msg))
53
54# Send the message via local SMTP server.
55with smtplib.SMTP('localhost') as s:
56    s.send_message(msg)
57