The solution of Chinese garbled problem in Python email application

Source: Internet
Author: User

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-^_^-)

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.