【问题标题】:When sending mail with SMTP it breaks utf-8 characters使用 SMTP 发送邮件时,它会破坏 utf-8 字符
【发布时间】: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}")

这里是“ma​​ilcontent.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


【解决方案1】:

我通过打开邮件内容文件解决了这个问题,如下:

message = open('mailcontent.txt', 'r', encoding='utf8').read()

【讨论】:

    猜你喜欢
    • 2021-12-18
    • 1970-01-01
    • 2017-02-20
    • 1970-01-01
    • 2022-01-09
    • 1970-01-01
    • 1970-01-01
    • 2011-06-25
    • 2021-11-01
    相关资源
    最近更新 更多