Python Forum

Full Version: Issue with text encoding ans smtplib.SMTP.sendmail()
You're currently viewing a stripped down version of our content. View the full version with proper formatting.
Hi and thanks for reading.

I have a prepared email that I want to send. This text is in a unicode(utf8) text file and displays correctly.
If I call sendmail(sender,receiver,msg) with msg being msg = file.read() I get

UnicodeEncodeError: 'ascii' codec can't encode character \xfc in position 1060: ordinal not in range(128)

I dont understand why it does Encode to Unicode in the first place, as the text is already in Unicode and all strings in python 3 are as well (by default), aren't they? If I use (sender,receiver,msg.encode('utf-8')) the email is sent, but non-ascii-chars are not shown correctly. I understand WHAT is happening: The UFT-8 Bytes are interpreted as ISO 8859-something, but I don't understand WHY this is happening and how I can do that correctly. That is porbably something I need to configure in smtplib, but what?

Please help. Thank you.
Issue solved: I read a textfile that had proper windows newlines (CRLF) and in python those were read as LF only. So I use file.read.replace("\x0A","\x0D\x0A").replace("\x0D\\x0D\\x0A","\x0D\x0A") - in case someone needs it.