python - 类型错误 : 'utf8' is an invalid keyword argument for Compat32 smtplib email error message

标签 python python-3.x email utf-8 smtplib

我之前可以使用下面的脚本发送个性化电子邮件,但突然出现以下错误。

我正在尝试从文件中读取姓名和电子邮件 ID,并向每个人发送个性化电子邮件。它从主题列表中随机选择一个主题并使用随机延迟。到目前为止它运行良好,但现在不行了。

*Traceback (most recent call last):
  File "C:/myprojects/normal_email.py", line 64, in <module>
    main()
  File "C:/myprojects/normal_email.py", line 57, in main
    smtp.send_message(msg)
  File "C:\Python\lib\smtplib.py", line 964, in send_message
    bytesmsg, policy=msg.policy.clone(utf8=True))
  File "C:\Python\lib\email\_policybase.py", line 72, in clone
    raise TypeError(
TypeError: 'utf8' is an invalid keyword argument for Compat32*

import csv
from string import Template
import smtplib
import random
import time
from email.mime.text import MIMEText
from email.mime.multipart import MIMEMultipart




template_file = r'C:\Users\91880\Desktop\template.txt'
filename = r'C:\Users\91880\Downloads\2307.csv'


#  reads the file and returns the names, emails in a list
def get_contacts(file):
    names_list = []
    emails_list = []
    with open(file, 'r') as mail_data:
        data = csv.reader(mail_data)
        for details in data:
            names_list.append(details[0])
            emails_list.append(details[1])
    return names_list, emails_list


# reads the template from a text file and returns
def get_template(file):
    with open(file, 'r') as template_info:
        template_data = template_info.read()
    return Template(template_data)


def main():
    email_user = '<a href="https://stackoverflow.com/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="016c78646c60686d416c60686d2f626e6c" rel="noreferrer noopener nofollow">[email protected]</a>'
    password = 'mypassword'

    subs = ['Hi', 'Hello']

    names, emails = get_contacts(filename)
    template = get_template(template_file)

    with smtplib.SMTP('smtp.office365.com', '587') as smtp:
        smtp.ehlo()
        smtp.starttls()
        smtp.ehlo()
        smtp.login(email_user, password)
        for name, email in zip(names, emails):
            subject = random.choice(subs)
            number = random.randint(10, 30)
            msg = MIMEMultipart()
            message = template.substitute(name=name.title())
            msg['From'] = email_user
            msg['To'] = email
            msg['Subject'] = subject
            msg.attach(MIMEText(message, 'html'))
            smtp.send_message(msg)
            print(f'sent email to {name} at {email}')
            del msg
            time.sleep(number)


if __name__ == '__main__':
    main()

最佳答案

发生此错误的原因是“收件人”或“发件人”地址之一中至少有一个非 ASCII 字符。应该可以通过将消息策略设置为 email.policy.default 来修复它。 :

from email import policy

...

msg = MIMEMultipart(policy=policy.default)

较新的EmailMessage/EmailPolicy自 Python 3.6 以来,API 优于旧的 email.mime 工具。使用首选工具,代码将如下所示:

from email.message import EmailMessage
from email import policy

...

            msg = EmailMessage(policy=policy.default)
            message = template.substitute(name=name.title())
            msg['From'] = email_user
            msg['To'] = email
            msg['Subject'] = subject
            msg.set_content(message, subtype='html')
            smtp.send_message(msg)

为了获得绝对的 RFC 兼容性,您可以考虑将策略设置为 SMTP ,生成 \r\n 行结尾。

关于python - 类型错误 : 'utf8' is an invalid keyword argument for Compat32 smtplib email error message,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/63063811/

相关文章:

python - 如何使用箭头增加日期?

python - 将变量从命令行解析为 url

python - 使用 Networkx to_agraph() 绘制图形

Python future 化而不用 old_div 替换/替换

email - Dovecot 不使用我的 mail_location

linux - Postfix 电子邮件转发

python - 模块未找到错误 : No module named 'pip._internal.cli'

python - 从数组绘制直方图

python - 需要 ASCII 扑克牌才能打印一行

python - 在 Python 中读取 Gmail 电子邮件