将标头添加到Django EmailMultiAlternatives

1ma*_*man 10 python email django smtp header

Django EmailMultiAlternatives文档中,没有关于如何添加诸如"format"或"Reply-To"之类的标题EmailMultiAlternatives.我花了一段时间才弄清楚,我发送这篇文章是为了帮助其他人节省时间.

正如您在django的源代码中所看到的,EmailMultiAlternatives继承自EmailMessage,因此它们在init构造函数中采用相同的参数.这样,我们可以添加如下标题:

msg = EmailMultiAlternatives(
    subject, message, from_email, to_list,
    headers={'Reply-To': "email@example.com", 'format': 'flowed'}
)
Run Code Online (Sandbox Code Playgroud)

Lyc*_*cum 2

早在 2015 年,OP 就抱怨说,文档中没有说明如何在 Django 邮件 (django.core.mail) 模块中添加“格式”和“回复”等标头。然而今天,虽然使用相同的文档链接。我们可以很容易地找到2018年的描述和例子:

\n\n
\n

EmailMessage[来源]

\n\n

EmailMessage使用以下参数初始化\n(如果 使用位置参数,则按给定顺序)。所有参数都是可选的,并且可以在调用方法之前随时设置。send()

\n\n
    \n
  • subject:电子邮件的主题行。
  • \n
  • 正文:正文。这应该是一条纯文本消息。
  • \n
  • from_email:发件人\xe2\x80\x99s 地址。和形式都是合法的fred@example.comFred <fred@example.com>如果省略,DEFAULT_FROM_EMAIL则使用 \n 设置。
  • \n
  • to:收件人地址的列表或元组。
  • \n
  • bcc:发送电子邮件时在 \xe2\x80\x9cBcc\xe2\x80\x9d 标头中使用的地址列表或元组。
  • \n
  • 连接:电子邮件后端实例。如果您想对多条消息使用同一连接,请使用此参数。send()如果省略,则在调用时创建\n 新连接。
  • \n
  • Attachments:要添加到邮件中的附件列表。这些可以是email.MIMEBase.MIMEBase实例,也可以是(filename, content, mimetype)三元组。
  • \n
  • headers:放置在消息上的额外标头的字典。键是标头名称,值是标头值。\xe2\x80\x99 由调用者负责确保电子邮件消息的标头名称和值的格式正确。对应的属性是extra_headers.
  • \n
  • cc:发送电子邮件时在 \xe2\x80\x9cCc\xe2\x80\x9d 标头中使用的收件人地址列表或元组。
  • \n
\n\n

例如:

\n\n
email = EmailMessage(\'Hello\', \'Body goes here\', \'from@example.com\',\n            [\'to1@example.com\', \'to2@example.com\'], [\'bcc@example.com\'],\n            headers = {\'Reply-To\': \'another@example.com\', \'format\': \'flowed\'})\n
Run Code Online (Sandbox Code Playgroud)\n
\n\n

正如我们从示例中看到的,也EmailMessageheaders参数(字典),EmailMultiAlternatives根据源代码中的文档字符串是:

\n\n
email = EmailMessage(\'Hello\', \'Body goes here\', \'from@example.com\',\n            [\'to1@example.com\', \'to2@example.com\'], [\'bcc@example.com\'],\n            headers = {\'Reply-To\': \'another@example.com\', \'format\': \'flowed\'})\n
Run Code Online (Sandbox Code Playgroud)\n\n

因此,如果您不需要特定的内容,EmailMessage也可以,因为目前EmailMultiAlternatives可以轻松包含文本和 HTML 版本的文本。

\n