【问题标题】:Setting email content from string in email.message?从 email.message 中的字符串设置电子邮件内容?
【发布时间】:2020-06-18 03:47:53
【问题描述】:

我想使用 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 似乎需要上下文管理器?

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

【问题讨论】:

    标签: python email


    【解决方案1】:

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

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

    添加带有主类型/子类型值的 Content-Type 标头。

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

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

    ...

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

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2013-09-26
      • 1970-01-01
      • 2023-03-31
      • 2021-05-31
      • 1970-01-01
      • 2019-10-05
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多