The problem
At work, I recently had to automatically create and send out emails. My tool of choice for this has been Python, which has a nice email module directly in the standard library.
Unfortunately, I hit multiple problems when trying to send messages to a receipient who's name contained non-ASCII characters.
Problem 1: The mailserver rejected the email, as headers were invalid.
To solve this, the Python docs mention the Header
class, which can be used to properly encode email headers before sending out.
Problem 2: Unfortunately, the example in the documentation is wrong and causes a bug, which has already been reported 3 years ago.
The solution
While the issue linked above mentions workarounds in the comments, none have worked for me.
After fiddling around a bit, I was able to solve the issue using the following approach:
By explicitly encoding the header, I was able to pass it successfully to the mailserver. Note that the maxlinelen
is required to prevent any newlines into the value, which causes another crash.