Python Forum

Full Version: [UnicodeEncodeError from smtplib]
You're currently viewing a stripped down version of our content. View the full version with proper formatting.
[UnicodeEncodeError from smtplib] 'ascii' codec can't encode character '\u2019' in position 77: ordinal not in range(128)

I'm trying to send an email where the Subject of the email will be title of articles. That means, this subject line will contain all types of non-ascii characters/symbols. The method I used for sending email is using smtplib.

The following is my email function:

def email(sender, pw, receiver, header, message):
    with smtplib.SMTP('smtp.gmail.com', 587) as smtp:
        smtp.ehlo()
        smtp.starttls()
        smtp.ehlo()

        smtp.login(sender, pw)

        subject = header
        body = message
        msg = f'Subject: {subject}\n\n{body}'

        smtp.sendmail(sender, receiver, msg)
And this is how I call my email function:

email_header = articleheader
email(my_email, my_pass, my_email, email_header, mymessage)
However, whenever my header contains any non-ascii characters, it will return the following error:

Error:
Traceback (most recent call last): File "<input>", line 1, in <module> File "C:\Program Files\JetBrains\PyCharm 2020.3.3\plugins\python\helpers\pydev\_pydev_bundle\pydev_umd.py", line 198, in runfile pydev_imports.execfile(filename, global_vars, local_vars) # execute the script File "C:\Program Files\JetBrains\PyCharm 2020.3.3\plugins\python\helpers\pydev\_pydev_imps\_pydev_execfile.py", line 18, in execfile exec(compile(contents+"\n", file, 'exec'), glob, loc) File "E:/DE Drive/Python Projects/rss_feed.py", line 186, in <module> email(my_email, my_pass, my_email, email_header, mymessage) File "E:/DE Drive/Python Projects/rss_feed.py", line 54, in email smtp.sendmail(sender, receiver, msg) File "C:\Users\nsmus\AppData\Local\Programs\Python\Python39\lib\smtplib.py", line 859, in sendmail msg = _fix_eols(msg).encode('ascii') UnicodeEncodeError: 'ascii' codec can't encode character '\u2019' in position 77: ordinal not in range(128)
with different '\.......' code in the list line of error message, depending on the character that causes the error.

From the error message and very little knowledge of mine reading the 'smtplib.py' script on github. It seems like msg = _fix_eols(msg).encode('ascii') this is the line that caused all the problem. I think I can easily fix this if this line of code is part of the script I wrote on my program. But, since, this line is part of smtplib library, I can't just go in there and fix it and seems to be something I am not capable of.

I'm just wondering, how can I make my script so that it can send the full message without missing any information.

Thank you very much!!!!


PS: Worst case: How to refer to "UnicodeEncodeError" from smtplib in try-except loop?
I thought I should be using smtplib.UnicodeEncodeError but that's not right.