embed picture in email using smtplib

Solutions on MaxInterview for embed picture in email using smtplib by the best coders in the world

showing results for - "embed picture in email using smtplib"
Mathilda
10 Jan 2020
1import smtplib
2from email import encoders
3from email.mime.multipart import MIMEMultipart
4from email.mime.text import MIMEText
5from email.mime.base import MIMEBase
6from email.mime.image import MIMEImage
7
8strFrom = 'zzzzzz@gmail.com'
9strTo = 'xxxxx@gmail.com'
10
11# Create the root message 
12
13msgRoot = MIMEMultipart('related')
14msgRoot['Subject'] = 'test message'
15msgRoot['From'] = strFrom
16msgRoot['To'] = strTo
17msgRoot['Cc'] =cc
18msgRoot.preamble = 'Multi-part message in MIME format.'
19
20msgAlternative = MIMEMultipart('alternative')
21msgRoot.attach(msgAlternative)
22
23msgText = MIMEText('Alternative plain text message.')
24msgAlternative.attach(msgText)
25
26msgText = MIMEText('<b>Some <i>HTML</i> text</b> and an image.<br><img src="cid:image1"><br>KPI-DATA!', 'html')
27msgAlternative.attach(msgText)
28
29#Attach Image 
30fp = open('test.png', 'rb') #Read image 
31msgImage = MIMEImage(fp.read())
32fp.close()
33
34# Define the image's ID as referenced above
35msgImage.add_header('Content-ID', '<image1>')
36msgRoot.attach(msgImage)
37
38import smtplib
39smtp = smtplib.SMTP()
40smtp.connect('smtp.gmail.com') #SMTp Server Details
41smtp.login('exampleuser', 'examplepass') #Username and Password of Account
42smtp.sendmail(strFrom, strTo, msgRoot.as_string())
43smtp.quit()
44