python发送html格式的邮件

python发邮件

 1 #!/usr/bin/python
 2 # -*- coding: UTF-8 -*-
 3 import smtplib
 4 from email.mime.text import MIMEText
 5 import string
 6 mailto_list=["[email protected]","XXX@163.com"]
 7 print mailto_list
 8 mail_host="smtp.exmail.qq.com"  #设置服务器
 9 mail_user="XX@qq.com"    #用户名
10 mail_pass="passwd"   #口令
11 neirong="<ul><li><font size=\"2\">12345</font></li></ul>"
12 
13 def send_mail(to_list,sub,content):     #定义一个函数,收件人、标题、邮件内容
14     me="hello"+"<"+mail_user+">"   #发件人定义,这里要和认证帐号一致才行的
15     msg = MIMEText(content,_subtype='html',_charset='utf-8') #这里看email模块的说明,这里构造内容
16     msg['Subject'] = sub
17     msg['From'] = me
18    # msg['To'] = string.join(mailto_list,",")  #这是2中的一种写法,通过string.join()函数,可以把元组中的各个字段以“,”分隔,和下面达到一样的效果
19     msg['To'] = ",".join(mailto_list)   #这种在2和3都可以用,在3中,string模块中取消了join()函数,join()函数作为一个全局函数被使用
20     try:
21         server = smtplib.SMTP()
22         server.connect(mail_host)
23         # server.starttls()
24         server.login(mail_user,mail_pass)
25         server.sendmail(me, to_list, msg.as_string())
26         server.close()
27         return True
28     except Exception, e:
29         print str(e)
30         return False
31 if __name__ == '__main__':    #做个判断,当直接调用的时候才执行这个函数,什么是直接调用?就是我直接执行这个脚本的时候就是直接调用,如果我在别的脚本导入这个脚本在执行就是间接调用
32     if send_mail(mailto_list,"hello",neirong):
33         print "发送成功"
34     else:
35         print "发送失败"

猜你喜欢

转载自www.cnblogs.com/fuqu/p/10016088.html
今日推荐