以下代码主要是解决发送邮件如果附件名字为中文显示乱码的问题。
# -*- coding: utf-8 -*- import email from email.MIMEText import MIMEText from email.MIMEMultipart import MIMEMultipart from email.MIMEBase import MIMEBase from email import encoders import smtplib import mimetypes from_addr = 'postmaster@test.org' to_addr = 'test@test.org' subject_header = 'Subject: 员工手册' p_w_upload = u'd:/员工手册.doc' #文件访问时候要求u,否则不能通过 body = '''欢迎加入******有限公司,请查阅附件''' m = MIMEMultipart() m["To"] = "wangzhenyu@spolo.org" m["From"] = "postmaster@spolo.org" m["Subject"] = subject_header ctype, encoding = mimetypes.guess_type(p_w_upload) print ctype, encoding maintype, subtype = ctype.split('/', 1) print maintype, subtype m.attach(MIMEText(body, 'plain', 'utf-8')) fp = open(p_w_upload, 'rb') msg = MIMEBase(maintype, subtype) msg.set_payload(fp.read()) fp.close() encoders.encode_base64(msg) msg.add_header("Content-Disposition", "p_w_upload", filename='员工手册.doc') m.attach(msg) smtp = smtplib.SMTP() smtp.connect('mail.test.org:25') smtp.login('postmaster@test.org', "password") smtp.sendmail('postmaster@stest.org', 'test@test.org', m.as_string()) smtp.quit() print '邮件发送成功'
已经测试通过,欢迎大家使用