pythonpython-2.7python-unicodemime-mail

UnicodeDecodeError: 'ascii' codec can't decode byte 0xe3


UnicodeDecodeError: 'ascii' codec can't decode byte 0xe3

I am facing this issue while running a mailing script in py 2.7 for the line...

msg.attach(MIMEText(welcome_msg + htmlMessageContent + footer_msg, 'html'))


Solution

  • One of the elements of the string you are concatenating

    welcome_msg + htmlMessageContent + footer_msg
    

    is Unicode, and another of them isn't. When you concatenate the strings Python has convert them all to a common type (Unicode), much as it does when you add an integer to a float. But the default string conversion to Unicode is ascii, and if the string contains a non-ascii character it will fail.

    Find out which string isn't Unicode. For this you can use type(). Wrap that string in a call to unicode() that explains how you want '\xe3' interpreted. For example, if '\xe3' should be interpreted as 'ã':

    unicode(mystring, encoding='Latin-1')
    

    Then your concatenation should work.