0

I'm receiving the following error while trying to send an email using the standard Python example

UnicodeDecodeError: 'ascii' codec can't decode byte 0xe3 in position 27: ordinal not in range(128)

Here is the code:

# Import smtplib for the actual sending function
import smtplib

# Import the email modules we'll need
from email.mime.text import MIMEText

# Open a plain text file for reading.  For this example, assume that
# the text file contains only ASCII characters.
fp = open(textfile, 'rb')
# Create a text/plain message
msg = MIMEText(fp.read())
fp.close()

# me == the sender's email address
# you == the recipient's email address
msg['Subject'] = 'The contents of %s' % textfile
msg['From'] = me
msg['To'] = you

# Send the message via our own SMTP server, but don't include the
# envelope header.
s = smtplib.SMTP('localhost')
s.sendmail(me, [you], msg.as_string())
s.quit()

Any ideas how to overcome this?

2 Answers2

0

If unicode is not important to you, you could try the following:

import unicodedata

str = fp.read()
normalized_message = unicodedata.normalize('NFKD', unicode(str, 'utf-8')).encode('ascii','ignore')
msg = MIMEText(normalized_message)

This will convert all unicode to the closest ASCII equivalent.

0

The code example says explicitly:

# For this example, assume that
# the text file contains only ASCII characters.

i.e., it is not expected to work if the input contains non-ascii characters. To send email that may contain non-ascii characters, use this answer.

Community
  • 1
  • 1
jfs
  • 399,953
  • 195
  • 994
  • 1,670