从 email.message 中的字符串设置电子邮件内容?

han*_*dle 3 python email

我想使用 Python 发送电子邮件。

有 sendmail (通过 python 的 sendmail 发送邮件),还有https://docs.python.org/3/library/smtplib.html它建议基于https://docs.python.org/3/library/email.message.html构建消息,并有一些示例https://docs.python.org/3/library/email.examples.html #email-examples从文件中读取消息内容:

# Open the plain text file whose name is in textfile for reading.
with open(textfile) as fp:
    # Create a text/plain message
    msg = EmailMessage()
    msg.set_content(fp.read())
Run Code Online (Sandbox Code Playgroud)

我试过了

msg.set_content(b"test message sent locally")
Run Code Online (Sandbox Code Playgroud)

但这会导致TypeError: set_bytes_content() missing 2 required positional arguments: 'maintype' and 'subtype'. 似乎https://docs.python.org/3/library/email.message.html#email.message.EmailMessage.set_content需要上下文管理器?

如何使用字符串来构造消息正文?

Ser*_*sta 6

该错误消息是正确的但具有误导性。默认的内容管理器(上下文管理器是不同的动物......)提供了这个set_content方法(强调我的):

email.contentmanager.set_content(msg, <'str'>, subtype="plain", charset='utf-8' cte=None, disposition=None, filename=None, cid=None, params=None, headers=None) 
email.contentmanager.set_content(msg, <'bytes'>, maintype, subtype, cte="base64", disposition=None, filename=None, cid=None, params=None, headers=None) 
email.contentmanager.set_content(msg, <'EmailMessage'>, cte=None, disposition=None, filename=None, cid=None, params=None, headers=None) 
email.contentmanager.set_content(msg, <'list'>, subtype='mixed', disposition=None, filename=None, cid=None, params=None, headers=None) 
Run Code Online (Sandbox Code Playgroud)

将标头和有效负载添加到 msg:

添加带有 maintype/subtype 值的 Content-Type 标头。

对于 str,将 MIME 主类型设置为 text,如果已指定,则将子类型设置为 subtype,如果未指定,则将 subtype 设置为 plain。

对于字节,使用指定的主类型和子类型,如果未指定,则引发 TypeError

...

长话短说,如果您想发送简单的短信,请将纯文本(unicode)字符串传递给set_content

msg.set_content("test message sent locally")    # pass a str string and not a byte string
Run Code Online (Sandbox Code Playgroud)