📜  使用 smtplib 在电子邮件中嵌入图片 - Python 代码示例

📅  最后修改于: 2022-03-11 14:46:01.126000             🧑  作者: Mango

代码示例1
import smtplib
from email import encoders
from email.mime.multipart import MIMEMultipart
from email.mime.text import MIMEText
from email.mime.base import MIMEBase
from email.mime.image import MIMEImage

strFrom = 'zzzzzz@gmail.com'
strTo = 'xxxxx@gmail.com'

# Create the root message 

msgRoot = MIMEMultipart('related')
msgRoot['Subject'] = 'test message'
msgRoot['From'] = strFrom
msgRoot['To'] = strTo
msgRoot['Cc'] =cc
msgRoot.preamble = 'Multi-part message in MIME format.'

msgAlternative = MIMEMultipart('alternative')
msgRoot.attach(msgAlternative)

msgText = MIMEText('Alternative plain text message.')
msgAlternative.attach(msgText)

msgText = MIMEText('Some HTML text and an image.

KPI-DATA!', 'html') msgAlternative.attach(msgText) #Attach Image fp = open('test.png', 'rb') #Read image msgImage = MIMEImage(fp.read()) fp.close() # Define the image's ID as referenced above msgImage.add_header('Content-ID', '') msgRoot.attach(msgImage) import smtplib smtp = smtplib.SMTP() smtp.connect('smtp.gmail.com') #SMTp Server Details smtp.login('exampleuser', 'examplepass') #Username and Password of Account smtp.sendmail(strFrom, strTo, msgRoot.as_string()) smtp.quit()