»Core Development>Code coverage>Doc/includes/email-alternative.py

Python code coverage for Doc/includes/email-alternative.py

#countcontent
1n/a#!/usr/bin/env python3
2n/a
3n/aimport smtplib
4n/a
5n/afrom email.message import EmailMessage
6n/afrom email.headerregistry import Address
7n/afrom email.utils import make_msgid
8n/a
9n/a# Create the base text message.
10n/amsg = EmailMessage()
11n/amsg['Subject'] = "Ayons asperges pour le déjeuner"
12n/amsg['From'] = Address("Pepé Le Pew", "pepe", "example.com")
13n/amsg['To'] = (Address("Penelope Pussycat", "penelope", "example.com"),
14n/a Address("Fabrette Pussycat", "fabrette", "example.com"))
15n/amsg.set_content("""\
16n/aSalut!
17n/a
18n/aCela ressemble à un excellent recipie[1] déjeuner.
19n/a
20n/a[1] http://www.yummly.com/recipe/Roasted-Asparagus-Epicurious-203718
21n/a
22n/a--Pepé
23n/a""")
24n/a
25n/a# Add the html version. This converts the message into a multipart/alternative
26n/a# container, with the original text message as the first part and the new html
27n/a# message as the second part.
28n/aasparagus_cid = make_msgid()
29n/amsg.add_alternative("""\
30n/a<html>
31n/a <head></head>
32n/a <body>
33n/a <p>Salut!</p>
34n/a <p>Cela ressemble à un excellent
35n/a <a href="http://www.yummly.com/recipe/Roasted-Asparagus-Epicurious-203718>
36n/a recipie
37n/a </a> déjeuner.
38n/a </p>
39n/a <img src="cid:{asparagus_cid}" />
40n/a </body>
41n/a</html>
42n/a""".format(asparagus_cid=asparagus_cid[1:-1]), subtype='html')
43n/a# note that we needed to peel the <> off the msgid for use in the html.
44n/a
45n/a# Now add the related image to the html part.
46n/awith open("roasted-asparagus.jpg", 'rb') as img:
47n/a msg.get_payload()[1].add_related(img.read(), 'image', 'jpeg',
48n/a cid=asparagus_cid)
49n/a
50n/a# Make a local copy of what we are going to send.
51n/awith open('outgoing.msg', 'wb') as f:
52n/a f.write(bytes(msg))
53n/a
54n/a# Send the message via local SMTP server.
55n/awith smtplib.SMTP('localhost') as s:
56n/a s.send_message(msg)