Search code examples
pythondjangoemailemail-headersdjango-email

What is the proper way to set the "From" header in an email using Django EmailMessage class?


I'm able to send an email and set most headers with no problem.

But this has been giving me odd results for quite some time now.

This is where I'm currently at:

email = EmailMessage(
    'My foobar subject!!',
    render_to_string(
        'emails/new_foobar_email.txt',
        {
            'foo': foo.something,
            'bar': bar.something,
        }
    ),
    'notify@foobar.com',
    [the_user.email, ],
    headers={'From ': 'Darth Vader <darth@vader.com>'},
)
email.send(
    fail_silently=False
)

When the email arrives, it says it is from "notify@foobar.com" and not "Darth Vader".

I've tried setting the headers like this:

# this way worked but was inconsistent. Some email clients showed it was from "unknown sender".
headers={'From ': 'Darth Vader'},

I've dug through this document about Internet Message Formats (RFC 2822) and it wasn't clear to me if I was following the best practice.

I also saw this SO Question, but it applies to the send_mail() function. It could be similar but it is different.

I'm not concerned with my email client displaying correctly (it could be tainted since I've been trying so many different ways and probably cached one of the ways that I was doing wrong..) but I'm concerned with following best practices so it will work for the majority of email clients.

Question

What is the proper way to set the "From" header in an email using EmailMessage class? And, what is the most compatible way with email clients?


Solution

  • You can put the details directly in the from argument:

    email = EmailMessage(
        'My foobar subject!!',
        body,
        'Darth Vader <notify@foobar.com>',
        [the_user.email])