-
Notifications
You must be signed in to change notification settings - Fork 307
/
html_email_attachments.py
45 lines (35 loc) · 1.11 KB
/
html_email_attachments.py
1
2
3
4
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
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
import smtplib
from email.message import EmailMessage
from email.utils import make_msgid
msg = EmailMessage()
asparagus_cid = make_msgid()
msg.set_content('This is a text message')
msg.add_alternative("""\
<html>
<head></head>
<body>
<p>Hello</p>
<p>
Here is an example of sending attachments in email using Python.
</p>
<img src="cid:{asparagus_cid}" />
</body>
</html>
""".format(asparagus_cid=asparagus_cid[1:-1]), subtype='html')
with open("sample.jpg", 'rb') as img:
msg.get_payload()[1].add_related(img.read(), 'image', 'jpeg', cid=asparagus_cid)
with open("sample.pdf", 'rb') as fp:
pdf_data = fp.read()
ctype = 'application/octet-stream'
maintype, subtype = ctype.split('/', 1)
msg.add_attachment(pdf_data, maintype=maintype, subtype=subtype, filename='sample.pdf')
fromEmail = 'gmail@gmail.com'
toEmail = 'gmail@gmail.com'
msg['Subject'] = 'HTML message with attachments'
msg['From'] = fromEmail
msg['To'] = toEmail
s = smtplib.SMTP('smtp.gmail.com', 587)
s.starttls()
s.login(fromEmail, 'gmail password')
s.send_message(msg)
s.quit()