Python SMTP邮件发送
程序员文章站
2022-03-18 09:33:00
...
带发送图片跟a标签的实例,以QQ邮箱为例
效果图:
注意点:
- multipart类型的选择(alternative、related)
代码展示:
#!python3
#coding:utf-8
#multipart类型主要有三种子类型:mixed/附件、alternative/超文本、related/内嵌资源pic
import smtplib,time
from email.mime.image import MIMEImage #生成包括多个部分的邮件体
from email.mime.multipart import MIMEMultipart #创建包含音频数据的邮件体
from email.mime.text import MIMEText #文件格式
from email.header import Header
for i in range(1):
time.sleep(1)
time_str=time.strftime('%Y/%m/%d %H:%M:%S', time.localtime(time.time()))
fromMail = 'aaa@qq.com' #验证信息
verif = 'xxxxx' #需要发短信开启smtp服务
toMail = 'aaa@qq.com'
msg = MIMEMultipart('related') #图片
msg['From'] = Header('Noc','utf-8')#header 头部信息定义
msg['To'] = Header('Noc','utf-8')
subject = 'Python SMTP '+ time_str
msg['Subject'] = Header(subject, 'utf-8')
msgAlternative = MIMEMultipart('alternative')#超文本
msg.attach(msgAlternative)
#文本信息
mail_msg = """
<p>Python 邮件发送测试...</p>
<p><a href="http://www.hao123.com">hao123</a></p>
<p>图片演示</p>
<p><img src="cid:image1"></p>
"""
msgAlternative.attach(MIMEText(mail_msg,'html','utf-8'))
#指定本地图片
pic = open('test.png','rb')
msgImage = MIMEImage(pic.read())
pic.close()
#定义图片 id,在HTML文本中引用
msgImage.add_header('Content-ID','<image1>')
msg.attach(msgImage)
try:
smtpObj = smtplib.SMTP('smtp.qq.com', 25)
smtpObj.ehlo() #服务器问好
smtpObj.starttls() #TLS 加密
smtpObj.login(fromMail, verif)
smtpObj.sendmail(fromMail, toMail, msg.as_string())
print('邮件发送成功 ' + time_str)
except smtplib.SMTPException:
print('Error:邮件发送失败 '+ time_str)
smtpObj.quit()
上一篇: JS中产生标识符方式的演变_javascript技巧
下一篇: 电子邮箱