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