Python基础 之 Python3 SMTP发送邮件 3
Python3 SMTP发送邮件
在 HTML 文本中添加图片
邮件的 HTML 文本中一般邮件服务商添加外链是无效的,正确添加图片的实例如下所示:
实例
!/usr/bin/python3
import smtplib
from email.mime.image import MIMEImage
from email.mime.multipart import MIMEMultipart
from email.mime.text import MIMEText
from email.header import Header
sender = 'from@baidu.com'
receivers = ['429240967@qq.com'] # 接收邮件,可设置为你的QQ邮箱或者其他邮箱
msgRoot = MIMEMultipart('related')
msgRoot['From'] = Header("百度", 'utf-8')
msgRoot['To'] = Header("测试", 'utf-8')
subject = 'Python SMTP 邮件测试'
msgRoot['Subject'] = Header(subject, 'utf-8')
msgAlternative = MIMEMultipart('alternative')
msgRoot.attach(msgAlternative)
mail_msg = """
Python 邮件发送测试...
图片演示:
"""
msgAlternative.attach(MIMEText(mail_msg, 'html', 'utf-8'))
指定图片为当前目录
fp = open('test.png', 'rb')
msgImage = MIMEImage(fp.read())
fp.close()
定义图片 ID,在 HTML 文本中引用
msgImage.add_header('Content-ID', '')
msgRoot.attach(msgImage)
try:
smtpObj = smtplib.SMTP('localhost')
smtpObj.sendmail(sender, receivers, msgRoot.as_string())
print ("邮件发送成功")
except smtplib.SMTPException:
print ("Error: 无法发送邮件")
$ python3 test.py
邮件发送成功