繁体   English   中英

如何在Python中发送带有某些非ASCII字符的电子邮件?

[英]How do I send an e-mail with some non-ASCII characters in Python?

我正在使用Python 3.7,并尝试使用smtplib发送电子邮件。 只要消息中不包含任何土耳其语字符(如“ş,ı,İ,ç,ö”),我的脚本就可以正常工作。 到目前为止,我找到的唯一"string=string.encode('ascii', 'ignore').decode('ascii')"解决方案是使用"string=string.encode('ascii', 'ignore').decode('ascii')"行,但是当我这样做时,字符串“ İşlem tamamlanmıştır." 成为"lem tamamlanmtr." 那么,如何保留原始字符串并绕过此错误呢?

代码的相关部分:

import smtplib
server = smtplib.SMTP_SSL(r'smtp.gmail.com', 465)
server.ehlo()
server.login(gmail_user, gmail_password)
message = 'Subject: {}\n\n{}'.format(subject, text)
server.sendmail(from, to, message)
server.close()

SMTP要求正确封装和标记所有非ASCII内容。 如果您知道自己在做什么,那么手工就不难了,但是简单而可扩展的解决方案是使用Python email库来构建有效的消息以传递给sendmail

这几乎完全照搬了Python email示例中的内容 它使用了在3.5版中正式使用的EmailMessage类,但应早于Python 3.3即可工作。

from email.message import EmailMessage

# Create a text/plain message
msg = EmailMessage()
msg.set_content(text)

msg['Subject'] = subject
msg['From'] = from
msg['To'] = to
import smtplib
from email.mime.text import MIMEText

text_type = 'plain' # or 'html'
text = 'Your message body'
msg = MIMEText(text, text_type, 'utf-8')
msg['Subject'] = 'Test Subject'
msg['From'] = gmail_user
msg['To'] = 'user1@x.com,user2@y.com'
server = smtplib.SMTP_SSL('smtp.gmail.com', 465)
server.login(gmail_user, gmail_password)
server.send_message(msg)
# or server.sendmail(msg['From'], msg['To'], msg.as_string())
server.quit()

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM