Search code examples
python-3.xencodingsmtplib

ASCII encoding error when sending an email in Python3?


I have a program in Python3 which sends mails. It works perfectly on several computers, but there is one in which not. I tried and this one only works when there are not any special characters like 'ñ' or 'á', 'é', etc...

I got the next error:

'ascii' codec can't encode character '\whatever' in position x: ordinal not in range(128)

And this is my code:

html = '<h1>niñería</h1>'
text = 'niñería'

mail = MIMEMultipart('alternative')
mail['From'] = '[email protected]'
mail['To'] = '[email protected]'
mail['Cc'] = ''
mail['Subject'] = 'My subject'

# Record the MIME types of both parts - text/plain and text/html.
part1 = MIMEText(text, 'plain')
part2 = MIMEText(html, 'html')

# Attach parts into message container. According to RFC 2046, the last
# part of a multipart message, in this case the HTML message, is best
# and preferred.
mail.attach(part1)
mail.attach(part2)

msg_full = mail.as_string()

server = smtplib.SMTP('smtp.gmail.com:587')
server.starttls()
server.login('[email protected]', 'my_password')
server.sendmail('[email protected]', ['[email protected]'], msg_full)
server.quit()

Is there any magic line like .encode('utf-8') or .decode('utf-8') which could make my email content recognised?


Solution

  • OK, solved. I only had to change the line:

    msg_full = mail.as_string()
    

    And write instead:

    msg_full = mail.as_string().encode()