【发布时间】:2021-03-07 17:54:02
【问题描述】:
我编写了一个用 Python 发送邮件的脚本。通常,此脚本将从 txt 文件中读取的文本作为电子邮件发送。 但是当邮件发送时,utf-8 字符会损坏。当我在 Linux 上运行这个脚本时,我没有收到这样的错误,但是当我在 Windows 上运行它时,我收到了这个错误。
这是我的代码:
try:
message = open('mailcontent.txt', 'r').read()
except Exception as e:
print(f"Error opening mail content file!: {e}")
def send_mail(messages, subject):
global msg
try:
msg = MIMEMultipart()
s = smtplib.SMTP(host="SMTP.office365.com", port=587)
s.starttls()
s.login(examplemailfrom, password)
msg['From'] = examplemailfrom
msg['To'] = examplemail
msg['Subject'] = examplesubject
msg.attach(MIMEText(message, 'plain', 'utf-8'))
s.send_message(msg)
del msg
except Exception as e:
print(f"An error has occurred!: {e}")
这里是“mailcontent.txt”文件内容:
Here İs an example mAİl
Almost all utf-8 characters get corrupted.
how can İ solve thİs?
邮件:
我该如何解决这个问题?
【问题讨论】:
-
open使用的默认编码不同。显式打开:message = open('mailcontent.txt', 'r', encoding='utf8').read() -
@MarkTolonen 似乎合乎逻辑。我试试看行不行再写
标签: python email utf-8 outlook smtp