发布于2019-09-03 16:21 阅读(834) 评论(0) 点赞(15) 收藏(5)
我正在编写一个带有身份验证的简单smtp-sender。这是我的代码
SMTPserver, sender, destination = 'smtp.googlemail.com', 'user@gmail.com', ['reciever@gmail.com']
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))
所以,第一次我指出text_subtype ='text',然后在标题中我放置一个msg ['Content-Type'] =“text / html; charset = utf-8”字符串。这是对的吗?
更新最后,我已经解决了我的消息问题你应该写像msg = MIMEText(content.encode('utf-8'),'plain','UTF-8')
from email.header import Header
from email.mime.multipart import MIMEMultipart
from email.mime.text import MIMEText
def contains_non_ascii_characters(str):
return not all(ord(c) < 128 for c in str)
def add_header(message, header_name, header_value):
if contains_non_ascii_characters(header_value):
h = Header(header_value, 'utf-8')
message[header_name] = h
else:
message[header_name] = header_value
return message
............
msg = MIMEMultipart('alternative')
msg = add_header(msg, 'Subject', subject)
if contains_non_ascii_characters(html):
html_text = MIMEText(html.encode('utf-8'), 'html','utf-8')
else:
html_text = MIMEText(html, 'html')
if(contains_non_ascii_characters(plain)):
plain_text = MIMEText(plain.encode('utf-8'),'plain','utf-8')
else:
plain_text = MIMEText(plain,'plain')
msg.attach(plain_text)
msg.attach(html_text)
无论文本是否包含非ASCII字符,这都应该为文本和标题提供正确的编码。它还意味着您不会不必要地自动使用base64编码。
作者:黑洞官方问答小能手
链接:https://www.pythonheidong.com/blog/article/86346/1f6753a670a90046de4f/
来源:python黑洞网
任何形式的转载都请注明出处,如有侵权 一经发现 必将追究其法律责任
昵称:
评论内容:(最多支持255个字符)
---无人问津也好,技不如人也罢,你都要试着安静下来,去做自己该做的事,而不是让内心的烦躁、焦虑,坏掉你本来就不多的热情和定力
Copyright © 2018-2021 python黑洞网 All Rights Reserved 版权所有,并保留所有权利。 京ICP备18063182号-1
投诉与举报,广告合作请联系vgs_info@163.com或QQ3083709327
免责声明:网站文章均由用户上传,仅供读者学习交流使用,禁止用做商业用途。若文章涉及色情,反动,侵权等违法信息,请向我们举报,一经核实我们会立即删除!