使用 HTML 正文在 Django 中创建一封电子邮件并包含一个附件

Create an email in django with an HTML body and includes an attachment

我可以发送 html 格式的文档作为电子邮件正文并包含附件吗?

send_mail() 具有 html_message 的选项,但 EmailMessage class 没有。

我的理解是发送附件需要使用EmailMessageclass使用attach_file方法

我错过了什么吗?我认为 send_mail() 使用 EmailMessage class,那么为什么这两个功能似乎相互排斥?

查看 EmailMultiAlternatives 它有一个 attach 函数,您可以将其用于此目的。

这是一个如何使用它的例子:

from django.core.mail import EmailMultiAlternatives

    subject         = request.POST.get('subject', '')
    message         = request.POST.get('message', '').encode("utf-8")

    # Create an e-mail
    email_message   = EmailMultiAlternatives(
        subject=subject,
        body=message,
        from_email=conn.username,
        to=recipents,
        bcc=bcc_recipents,  # ['bcc@example.com'],
        cc=cc_recipents,
        headers = {'Reply-To': request.user.email},
        connection = connection
        )

    email_message.attach_alternative(message, "text/html")

    for a in matachments:

        email_message.attach(a.name, a.document.read())

    email_message.send()

我看到要有一个 html 电子邮件,我可以将 html 作为正文,但我只需要将 content_subtype 更改为 html。

msg_body.content_subtype = "html"

感谢您的帮助,它让我回到了正确的页面以更详细地阅读。