python HTML格式发送邮件

登录qq邮箱:设置->账户 找到如图片处开启smtp
通过第三方发送邮件都需开启POP3/IMAP/SMTP/Exchange/CardDAV/CalDAV服务,本人用的qq邮箱进行发送详情请点击http://service.mail.qq.com/cgi-bin/help?subtype=1&no=167&id=28
python HTML格式发送邮件_第1张图片
以下是代码:

import smtplib
from email.mime.text import MIMEText
from email.mime.multipart import MIMEMultipart
from email.header import Header

msg_from = '**********@qq.com'  # 发送方邮箱
passwd = 'mizfilyvxaxajgfe'  # 填入发送方邮箱的授权码
msg_to = '**************@sina.cn'  # 收件人邮箱

 # 创建一个带附件的实例
message = MIMEMultipart()
message['From'] = Header("冰石头", 'utf-8')
message['To'] = Header("收件人名称", 'utf-8')
subject = 'Python SMTP 邮件测试' # 主体内容
 #subject = unicode(subject)# 更改主题编码
message['Subject'] = Header(subject, 'utf-8')
'''
mail_msg = """

冰石头正在进行邮件发送测试...

冰石头

""" message.attach(MIMEText(mail_msg, 'html', 'utf-8'))如果要发送html需要将plain改成html ''' # 邮件正文内容 message.attach(MIMEText('冰石头正在进行邮件发送测试……', 'plain', 'utf-8')) # 构造附件1,传送当前目录下的 test.txt 文件 att1 = MIMEText(open('test.txt', 'rb').read(), 'base64', 'utf-8') att1["Content-Type"] = 'application/octet-stream' # 这里的filename可以任意写,写什么名字,邮件中显示什么名字 att1["Content-Disposition"] = 'attachment; filename="demo.txt"' message.attach(att1) try: smtpObj = smtplib.SMTP_SSL("smtp.qq.com", 465) # qq邮箱的smtp地址及端口号 smtpObj.login(msg_from, passwd) smtpObj.sendmail(msg_from, msg_to, message.as_string()) print "邮件发送成功" except smtplib.SMTPException: print "Error: 无法发送邮件"

最后如果我的文章对您起到了帮助,那动动手指为我点个赞吧!
有问题,请留言,我是闷闷的冰石头

欢迎转载交流

你可能感兴趣的:(python)