gpt4 book ai didi

python - 将标题添加到 Django EmailMultiAlternatives

转载 作者:太空狗 更新时间:2023-10-29 19:29:28 24 4
gpt4 key购买 nike

Django EmailMultiAlternatives documentation没有关于如何在 EmailMultiAlternatives 中添加标题(如“格式”或“回复”)的内容。我花了一段时间才弄明白,我发送这篇文章是为了帮助其他人节省时间。

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

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

最佳答案

早在 2015 年,OP 就提示说,文档中没有说明如何在 Django 邮件 (django.core.mail) 模块中添加标题,例如“格式”和“回复”。然而今天,在使用 same documentation link 时.我们可以轻松找到 2018 年的描述和示例:

class EmailMessage[source]

The EmailMessage class is initialized with the following parameters (in the given order, if positional arguments are used). All parameters are optional and can be set at any time prior to calling the send() method.

  • subject: The subject line of the email.
  • body: The body text. This should be a plain text message.
  • from_email: The sender’s address. Both fred@example.com and Fred <fred@example.com> forms are legal. If omitted, the DEFAULT_FROM_EMAIL setting is used.
  • to: A list or tuple of recipient addresses.
  • bcc: A list or tuple of addresses used in the “Bcc” header when sending the email.
  • connection: An email backend instance. Use this parameter if you want to use the same connection for multiple messages. If omitted, a new connection is created when send() is called.
  • attachments: A list of attachments to put on the message. These can be either email.MIMEBase.MIMEBase instances, or (filename, content, mimetype) triples.
  • headers: A dictionary of extra headers to put on the message. The keys are the header name, values are the header values. It’s up to the caller to ensure header names and values are in the correct format for an email message. The corresponding attribute is extra_headers.
  • cc: A list or tuple of recipient addresses used in the “Cc” header when sending the email.

For example:

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

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

A version of EmailMessage that makes it easy to send multipart/alternative
messages. For example, including text and HTML versions of the text is
made easier.

因此,如果您不需要特定的东西,EmailMessage很好,因为目前 EmailMultiAlternatives用于轻松包含文本和文本的 HTML 版本。

关于python - 将标题添加到 Django EmailMultiAlternatives,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29353815/

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