我正在寫一個簡單的驗證smtp發件人。這是我的代碼如何在Python 2.7中使用smtplib在電子郵件中設置字符集?
SMTPserver, sender, destination = 'smtp.googlemail.com', '[email protected]', ['[email protected]']
USERNAME, PASSWORD = "user", "password"
# typical values for text_subtype are plain, html, xml
text_subtype = 'plain'
content="""
Hello, world!
"""
subject="Message Subject"
from smtplib import SMTP_SSL as SMTP # this invokes the secure SMTP protocol (port 465, uses SSL)
# from smtplib import SMTP # use this for standard SMTP protocol (port 25, no encryption)
from email.MIMEText import MIMEText
try:
msg = MIMEText(content, text_subtype)
msg['Subject']= subject
msg['From'] = sender # some SMTP servers will do this automatically, not all
conn = SMTP(SMTPserver)
conn.set_debuglevel(False)
conn.login(USERNAME, PASSWORD)
try:
conn.sendmail(sender, destination, msg.as_string())
finally:
conn.close()
except Exception, exc:
sys.exit("mail failed; %s" % str(exc)) # give a error message
它工作完美,直到我嘗試發送非ASCII符號(俄羅斯西里爾文)。我應該如何在消息中定義一個字符集以使其以適當的方式顯示?提前致謝!
UPD。我已經改變了我的代碼:
text_subtype = 'text'
content="<p>Текст письма</p>"
msg = MIMEText(content, text_subtype)
msg['From']=sender # some SMTP servers will do this automatically, not all
msg['MIME-Version']="1.0"
msg['Subject']="=?UTF-8?Q?Тема письма?="
msg['Content-Type'] = "text/html; charset=utf-8"
msg['Content-Transfer-Encoding'] = "quoted-printable"
…
conn.sendmail(sender, destination, str(msg))
所以,我第一次spectify text_subtype = '文本',然後在頭我把一個味精[ '內容類型'] =「text/html的;字符集= UTF -8「字符串。這是對的嗎?
UPDATE最後,我已經解決了我的問題的消息 你應該寫像味精=未便MimeText用於(content.encode( 'UTF-8'), '普通', 'UTF-8')
嗨Lorcan!如果我要在我的消息中指定它們(比如msg ['From'] ='[email protected]'),那麼'To'和'From'如何?我應該對它進行編碼呢? – 2017-10-24 12:26:12