Monday, March 27, 2023

Setting recipient name in EmailMultiAlternatives


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()} <{}>")

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(),` 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,` 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(),, 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?


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
To view this discussion on the web visit

No comments:

Post a Comment