I want a Windows program that should be able to automatically send emails. I have written the code in Python, tested it locally on Fedora, then built an .exe using PyInstaller in a virtual German windows 10 and tried it there and it worked like a charm. Then I deployed the .exe on the target German Windows 10 machine and it always throws a UnicodeEncodeError. Here is the relevant part of my code:
msg = EmailMessage()
msg['From'] = username
msg['To'] = to_addr
msg['Subject'] = subject
msg.set_content(body, charset='utf-8')
with smtplib.SMTP(smtp_server, smtp_port) as server:
if use_tls:
server.starttls()
server.login(self.username, self.password)
server.send_message(msg)
And here is my error trace:
Traceback (most recent call last):
File "main.py", line 68, in place_order
File "order_mailer.py", line 133, in place_order
File "smtplib.py", line 769, in starttls
File "smtplib.py", line 611, in ehlo_or_helo_if_needed
File "smtplib.py", line 451, in ehlo
File "smtplib.py", line 378, in putcmd
File "smtplib.py", line 357, in send
UnicodeEncodeError: 'ascii' codec can't encode character '\xfc' in position 10: ordinal not in range(128)
The Unicode character \xfc should be the German ü if I am right. I would need this character in the final deployment, but I did not use it in the subject neither the body or elsewhere in my test environment.
I tried encoding the headers:
msg['From'] = Header(username, 'utf-8').encode()
msg['To'] = Header(to_addr, 'utf-8').encode()
msg['Subject'] = Header(subject, 'utf-8').encode()
This still works in my virtual test system, but does not change anything on the real system.
EDIT: This question seems to be similar, but I am using the send_message function, not sendmail. I also tried switching to sendmail and handing it bytes, but this did not work. As the trace suggests, the error already occurs in starttls, before sending the message.
print()(andprint(type(...)),print(len(...)), etc.) to see which part of code is executed and what you really have in variables. It is called"print debugging"and it helps to see what code is really doing.