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

孤街醉人 提交于 2021-01-28 07:50:31

问题


I am using Python 3.7 and trying to send e-mails with smtplib. My script works flawlessly so long as the message doesn't contain any Turkish characters such as "ş,ı,İ,ç,ö". The only solution I have found so far that works is using the "string=string.encode('ascii', 'ignore').decode('ascii')" line but when I do that, the string "İşlem tamamlanmıştır." becomes "lem tamamlanmtr.". So how can I keep the original string and bypass this error?

The relevant part of the code:

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()

回答1:


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()



回答2:


SMTP requires any non-ASCII content to be encapsulated and tagged properly. If you know what you are doing, this isn't hard to do by hand, but the simple and scalable solution is to use the Python email library to build a valid message to pass to sendmail.

This is adapted pretty much verbatim from the Python email example. It uses the EmailMessage class which became official in 3.5, but should work as early as 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


来源:https://stackoverflow.com/questions/56759272/how-do-i-send-an-e-mail-with-some-non-ascii-characters-in-python

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!