RandO
RandO

Reputation: 355

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

Can I send an html formatted document as the body of an email and include an attachment?

send_mail() has an option for html_message but the EmailMessage class does not.

My understanding is that to send an attachment, I need to use the EmailMessage class to use the attach_file method.

Am I missing something? I thought send_mail() uses the EmailMessage class, so why do these two features seem mutually exclusive?

Upvotes: 0

Views: 1347

Answers (2)

RandO
RandO

Reputation: 355

I see that to have an html email, I can have html as the body, but I just need to change the content_subtype to html.

msg_body.content_subtype = "html"

Thanks for your help, it got me back to the right page to read in better detail.

Upvotes: 0

Gustavo Reyes
Gustavo Reyes

Reputation: 1344

Check out EmailMultiAlternatives it has an attach function that you can use for this purpose.

Here's an example of how to use it:

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,  # ['[email protected]'],
        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()

Upvotes: 1

Related Questions