Setting recipient name in EmailMultiAlternatives

11 views
Skip to first unread message

Sylvain

unread,
Mar 27, 2023, 8:53:56 AM3/27/23
to Django users
Hello,

I’m using the following code to send mails to my users, with their name appearing in the `To` header:

msg = EmailMultiAlternatives(subject=subject, body=body, to=f"{user.get_full_name()} <{user.email}>")
msg.send()

It works fine but if you have a special character in your name (such as a comma) then `msg.send()` will fail because `sanitize_address` raises an exception. Note that this will only fail with the SMTP backend because all other backends (such as the console backend) don’t sanitize the address, so even if you try to write tests for this case, it won’t fail unless you actually use the SMTP backend.

I couldn’t find any indication in the Django docs on how to correctly include the name of the recipient in an e-mail so I started digging in the code. I found that the `sanitize_address` function (which uses the email.headerregistry.parser module of Python’s, which doesn’t seem to be documented) accepts either a string or a tuple of (name, address), so I thought I could use `to=(user.get_full_name(), user.email)` which seemed quite elegant, but doesn’t really work because the value is not sanitized before it’s put in the `To` header so it will show up like `(Jane Doe, ja...@example.com)` in the recipient mailbox.

However, it seems calling `sanitize_address` directly works, like so:

msg = EmailMultiAlternatives(subject=subject, body=body, to=sanitize_address((user.get_full_name(), user.email), settings.DEFAULT_CHARSET))

But since there’s no mention of `sanitize_address` in the Django docs, I’m not sure it’s the right way to do it. And since I couldn’t find anything on this topic on the internet I think I might be missing something obvious. Could anyone point me in the right direction?

Thanks!

Peter Benjamin Ani

unread,
Mar 27, 2023, 9:13:15 AM3/27/23
to django...@googlegroups.com
I don't fully understand the error, can you describe it more please 

--
You received this message because you are subscribed to the Google Groups "Django users" group.
To unsubscribe from this group and stop receiving emails from it, send an email to django-users...@googlegroups.com.
To view this discussion on the web visit https://groups.google.com/d/msgid/django-users/9f64152c-a5b3-4995-a539-1359416e9decn%40googlegroups.com.

Sharif Mehedi

unread,
Mar 27, 2023, 9:30:57 AM3/27/23
to django...@googlegroups.com
I haven't read the documents myself that I am referring to here. But they should come as a help to you with your question.

Try to follow the generalized rules when having some public namespace ( or address).

Regards,
--
Sharif
Reply all
Reply to author
Forward
0 new messages