Reputation: 5734
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,
}
),
'[email protected]',
[the_user.email, ],
headers={'From ': 'Darth Vader <[email protected]>'},
)
email.send(
fail_silently=False
)
When the email arrives, it says it is from "[email protected]" 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?
Upvotes: 0
Views: 770
Reputation: 5734
email = EmailMessage(
'My foobar subject!!',
render_to_string(
'emails/new_foobar_email.txt',
{
'foo': foo.something,
'bar': bar.something,
}
),
'[email protected]',
[the_user.email, ],
headers={'From': 'Darth Vader <[email protected]>'},
)
email.send(
fail_silently=False
)
The key thing I did wrong was having a trailing space after "From". So this will work.
However. I'm going to simplify the code and do as @Daniel Roseman suggested and put the display name in the from argument and not use the headers key words.
Upvotes: 0
Reputation: 599610
You can put the details directly in the from
argument:
email = EmailMessage(
'My foobar subject!!',
body,
'Darth Vader <[email protected]>',
[the_user.email])
Upvotes: 1