1
votes
# -*- coding: utf-8 -*-
#!/usr/bin/python3
import smtplib

gmail_user = 'X@X'
gmail_password = 'XXX'

from_add = gmail_user
to = ["X@X"]
subject ="主旨(subject)"
body ="內容(content)"
email_text = """\
From: %s
To: %s
Subject: %s
%s
"""%(from_add, ", ".join(to), subject, body)


try:
    smtpObj = smtplib.SMTP('smtp.gmail.com', 587)
    smtpObj.ehlo()
    smtpObj.starttls()
    smtpObj.login(gmail_user, gmail_password)
    smtpObj.sendmail(from_add, to, email_text)
    smtpObj.close()
    print('Email sent')
except UnicodeEncodeError as err:
    print('{}'.format(err))
except:
    print("err")

I got the UnicodeEncodeError:

'ascii' codec can't encode characters in position 73-74: ordinal not in range(128)

Isn't python3 defult encoding be 'UTF-8'??

when I run this script

It actually python3.5.2

when I print the type of body ,it is str

but the error seems like be asciicode not unicode for python2

thx

1

1 Answers

2
votes

smtplib.SMTP.sendmail expects its msg argument to be a str containing only ascii characters or a bytes:

msg may be a string containing characters in the ASCII range, or a byte string. A string is encoded to bytes using the ascii codec, and lone \r and \n characters are converted to \r\n characters. A byte string is not modified.

Your message is a string, but in contains non-ascii characters; you need to encode to bytes:

smtpObj.sendmail(from_add, to, email_text.encode('utf-8'))