首页 > 代码库 > python 发送html邮件

python 发送html邮件

简单的python发送html邮件代码,如下:

#!/usr/bin/env python
#-*- coding:utf-8 -*-
import smtplib
from email.header import Header
from email.MIMEText import MIMEText
from email.mime.multipart import MIMEMultipart
########################################################################
MailHost = "mail.xxxx.com"
MailUser = "user@xxxx.com"
MailPswd = "password"
MailPostfix = "xxxx.com"
########################################################################
def Mail(sendmail,sub):
    Me = MailUser
    msg = MIMEMultipart()
    #组装信头
    msg[‘Subject‘] = Header(sub,‘utf-8‘)
    #使用国际化编码
    msg[‘From‘] = r"%s <%s>" % (Header("测试邮件","utf-8"),Me)
    #添加多个邮箱的时候以逗号隔开
    sendmaillist=sendmail.split(",")
    msg[‘To‘] = ";".join(sendmaillist)
    #html
    #读取html文件
    html = open(‘test.html‘).read()
    #实例化为html部分,并设置编码
    html_part = MIMEText(html,‘html‘,‘utf-8‘)
    #绑定到message里
    msg.attach(html_part)
    #send mail
    try:
        s = smtplib.SMTP()
        s.connect(MailHost)
        s.login(MailUser, MailPswd)
        s.sendmail(Me, sendmaillist, msg.as_string())
        s.close()
        return True
    except Exception, e:
        print str(e)
        return False
if __name__ == "__main__":
    maillist = "test1@qq.com,test2@163.com"
    sub = "测试标题"
    Mail(maillist,sub)


本文出自 “学海无涯苦作舟” 博客,请务必保留此出处http://linuxshow.blog.51cto.com/1572053/1408485