gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-02 02:58:31 24 4
gpt4 key购买 nike

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

有 sendmail ( Sending mail via sendmail from python ),还有 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())

我试过了

msg.set_content(b"test message sent locally")

但这会导致 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需要上下文管理器?

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

最佳答案

错误消息是正确的但具有误导性。默认内容管理器(上下文管理器是另一种动物...)提供此 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)

Add headers and payload to msg:

Add a Content-Type header with a maintype/subtype value.

For str, set the MIME maintype to text, and set the subtype to subtype if it is specified, or plain if it is not.

For bytes, use the specified maintype and subtype, or raise a TypeError if they are not specified.

...

长话短说,如果你想发送一条简单的文本消息,将一个纯 (unicode) 字符串传递给 set_content:

msg.set_content("test message sent locally")    # pass a str string and not a byte string

关于python - 从 email.message 中的字符串设置电子邮件内容?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60546601/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com