Or to Python's Unicode understanding is not thorough, often encountered a variety of Chinese garbled problem, today, in the email application, Chinese garbled again out of trouble, after a time of the mistake, made a solution:
#-*-Coding:utf-8-*-
'''
Created on 2010-6-21
@author: Administrator
'''
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 = ' qgb@123.com '
to_addr = ' kbx@123.com '
Subject_header = ' Subject: Patrol report '
Attachment = U ' e:/python/database patrol record table. xls ' #文件访问时候要求u, otherwise can't pass
BODY = ' Patrol report '
m = Mimemultipart ()
M["to"] = To_addr
M["from"] = From_addr
m["Subject"] = Subject_header
CType, encoding = Mimetypes.guess_type (attachment)
Print CType, encoding
MainType, subtype = ctype.split ('/', 1)
Print MainType, subtype
M.attach (Mimetext (body, ' plain ', ' utf-8 ') #明确body的编码是utf-8
fp = open (attachment, ' RB ')
msg = Mimebase (MainType, subtype)
Msg.set_payload (Fp.read ())
Fp.close ()
Encoders.encode_base64 (msg)
Msg.add_header ("Content-disposition", "attachment", filename= ' Patrol report. xls ')
#encoders. Encode_base64 (msg) #将http头信息再进行一次编码, otherwise the Chinese name of the attachment cannot be used
#上面一句有误
M.attach (msg)
s = smtplib. SMTP (' mail.123.com ')
S.set_debuglevel (1)
S.sendmail (From_addr, To_addr, m.as_string ())
S.quit ()
Resources:
1, Python for UNIX and Linux System Administration, Noab Gift & Jeremy M.Jones, p147-150
2, through Google to find the network of the Brothers and sisters blogs (not listed here, but to a piece of gratitude-^_^-)