使用python smtp发邮件代码
2010-06-11 16:41
701 查看
#!/usr/bin/env python # -*- coding: gbk -*- #导入smtplib和MIMEText import smtplib from email.mime.text import MIMEText ############# # 要发给谁,这里发给2个人 mailto_list=["aaa@juyimeng.com","bbb@juyimeng.com"] ##################### # 设置服务器,用户名、口令以及邮箱的后缀 mail_host="smtp.126.com" mail_user="xxx" mail_pass="yyy" mail_postfix="126.com" ###################### def send_mail(to_list,sub,content): ''' to_list:发给谁 sub:主题 content:内容 send_mail("aaa@126.com","sub","content") ''' me=mail_user+"<"+mail_user+"@"+mail_postfix+">" msg = MIMEText(content) msg['Subject'] = sub msg['From'] = me msg['To'] = ";".join(to_list) try: s = smtplib.SMTP() s.connect(mail_host) s.login(mail_user,mail_pass) s.sendmail(me, to_list, msg.as_string()) s.close() return True except Exception, e: print str(e) return False if __name__ == '__main__': if send_mail(mailto_list,"subject","content"): print "发送成功" else: print "发送失败"
按照上面的代码执行之后,提示我
Traceback (most recent call last):
File "/usr/local
b/python2.6/threading.py", line 525, in __bootstrap_inner
File "/home/houjw/monitor/DbMonitorThread.py", line 117, in run
File "/home/houjw/monitor/Alarm.py", line 15, in report
File "/home/houjw/monitor/myemail.py", line 23, in send_mail
File "/usr/local
b/python2.6/email/mime/text.py", line 30, in __init__
File "/usr/local
b/python2.6/email/message.py", line 224, in set_payload
File "/usr/local
b/python2.6/email/message.py", line 264, in set_charset
File "/usr/local
b/python2.6/email/encoders.py", line 73, in encode_7or8bit
LookupError: unknown encoding: ascii
在同事的指导下在执行代码前添加
reload(sys)
sys.setdefaultencoding('utf8')
就好了
email.mime.text.
MIMEText
class email.mime.text.MIMEText(_text[, _subtype[, _charset]])
Module: email.mime.text
A subclass of MIMENonMultipart, the MIMEText class is used to create MIME objects of major type text. _text is the string for the payload. _subtype is the minor type and defaults to plain. _charset is the character set of the text and is passed as a parameter to the MIMENonMultipart constructor; it defaults to us-ascii. If _text is unicode, it is encoded using the output_charset of _charset, otherwise it is used as-is
推荐使用下面这种
msg = email.MIMEText.MIMEText(info, _subtype="html", _charset="utf-8") http://suzhouclark.itpub.net/post/7184/484998
相关文章推荐
- Python 使用SMTP发送邮件的代码小结
- python使用两种发邮件的方式smtp和outlook示例
- 简单的python smtp发邮件代码
- php下使用SMTP发邮件的代码
- python3 SMTP 发邮件 通过测试完整代码
- Python 使用SMTP发送邮件的代码小结
- [Python]使用smtplib类库发邮件
- php下使用SMTP发邮件的代码
- python实现SMTP发邮件(不需要注册邮箱使用邮箱的SMTP服务)
- 使用python偷偷发邮件
- 使用Python对Csv文件操作实例代码
- Python使用poplib模块和smtplib模块收发电子邮件的教程
- 【备忘】使用FME PythonCaller的基本代码结构
- 使用python实现细菌繁殖的算法代码,欢迎拍砖讨论!
- Caffe学习(九)使用Nsight Eclipse调试py-faster-rcnn(C++/python混合代码调试)
- 用两种不同的方法导出ORACLE 查询数据为CSV 文件 (python 代码 与 使用 utl_file 包)
- python应用系列教程——python使用smtp上传邮件,使用pop3下载邮件
- pngCanvas 是一个使用纯Python代码的生成png图像的工具
- 如何使用 Pylint 来规范 Python 代码风格
- Python使用装饰器进行django开发实例代码