I’ve got a case in which sending an e-mail with non UTF8 characters (ie “à”), causes a crash with:
sendmail.py", line 40, in sendmail
senderrs = server.sendmail(from_addr, to_addrs, msg.as_string())
File "/usr/lib/python3.9/smtplib.py", line 859, in sendmail
msg = _fix_eols(msg).encode('ascii')
UnicodeEncodeError: 'ascii' codec can't encode character '\xe0' in position 213: ordinal not in range(128)
My code looks like this:
msg = MIMEText('Gràcies', 'html', _charset='utf-8')
msg['From'] = from_addr
msg['To'] = ', '.join(to_addr)
msg['Subject'] = Header("Hola", 'utf-8')
sendmail(from_addr, to_addr, msg)
The thing is that I can prevent the issue with this simple patch, which basically lets SMTP class to convert the e-mail message before sending:
--- a/trytond/sendmail.py
+++ b/trytond/sendmail.py
@@ -36,7 +36,7 @@ def sendmail(from_addr, to_addrs, msg, server=None, strict=False):
if 'Date' not in msg:
msg['Date'] = formatdate()
try:
- senderrs = server.sendmail(from_addr, to_addrs, msg.as_string())
+ senderrs = server.send_message(msg, from_addr, to_addrs)
except Exception:
if strict:
raise
Am I doing something wrong? Would it make more sense to use send_message()?