From: http://outofmemory.cn/code-snippet/1464/python-send-youjian-resolve-suoyou-luanma-question
Using Python to send e-mails is simple, but it's annoying to have garbled problems. Garbled problem has several: there is a sender name garbled, there is a title garbled, there is a problem with the body garbled.
To resolve the sender name garbled problem, you must use the header, the following code:
From email. Importheaderfrom=("%s<[email protected]>")%(header(' outofmemory.cn admin ',' Utf-8 '),)
By setting the sender in this way, the sender's display will not have a garbled appearance.
Message subject garbled problem
The message subject garbled may be in some mailboxes appear, for example, I have been sent to Gmail will not garbled, but sent to sina.cn mailbox will be garbled.
To solve the problem of garbled message subject needs to ensure that subject must be Unicode, as follows:
If not isinstance(subject,Unicode):= Unicode(subject) msg[' Subject ']= Subject
Solve the message body garbled problem
You first need to specify Mimetext as the Utf-8 encoding, and then set the msg[' Accept-language ' and msg[' Accept-charset '] two properties, as in the following code snippet:
=mimetext(body,format,' Utf-8 ') msg["Accept-language"] ="ZH-CN" msg["Accept-charset"]= "iso-8859-1,utf-8 "
Solve the above three problems, the message garbled problem does not exist, the following is the full email code:
ImportSmtplibFromEmail.Mime.TextImport MimetextFromEmail.HeaderImport Header#下面一行要设置成你自己的邮件服务器的地址以及用户名密码发件人信息Host,User,Password,Frommail=SmtpinfoDefSendMail(mailto,Subject,Body,Format=' Plain '): IfIsinstance(Body,Unicode):Body=Str(Body)Me= ("%s<"+Frommail+">") % (Header(_mailfrom,' Utf-8 '),)Msg= Mimetext(Body,Format,' Utf-8 ') If NotIsinstance(Subject,Unicode):Subject=Unicode(Subject)Msg[' Subject '] =Subject MSG[' From '] =Me msg[' To '] =mailto msg["Accept-language"]="ZH-CN"Msg["Accept-charset"]="Iso-8859-1,utf-8" Try:S=Smtplib.Smtp()S.Connect(Host)S.Login(User,Password)S.sendmail (me, mailto< Span class= "pun" >, Msg. () S. () return true< Span class= "PLN" > except exception, E: print str (e) return false
The above program test sent to gmail,sina,qq,163 and Hotmail, there is no garbled problem.
Python sends garbled messages