使用 SMTP 发送邮件时,它会破坏 utf-8 字符
When sending mail with SMTP it breaks utf-8 characters
我写了一个用 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?
邮箱:
我该如何解决这个问题?
我通过如下打开邮件内容文件解决了这个问题:
message = open('mailcontent.txt', 'r', encoding='utf8').read()
我写了一个用 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?
邮箱:
我该如何解决这个问题?
我通过如下打开邮件内容文件解决了这个问题:
message = open('mailcontent.txt', 'r', encoding='utf8').read()