简体   繁体   中英

how python sendmail with chinese characters?

My environment is python3.3.4 django1.6.2,when I work on a django project,and I need to send email to my users through a email proxy service,but I went wrong with the django's send_mail. So I wrote a function with python's stmplib and email Lib.The code is like:

def email_user(context):


fromEmail = 'admin@***.cn'
toEmail = ['***@qq.com']
msg = MIMEMultipart('alternative')
msg.set_charset('utf8')
msg['Subject'] = '欢迎注册心优雅社区,请激活您的账号'
msg['From'] = fromEmail
msg['To'] = ','.join(toEmail)
html = """
亲爱的%(username)s:

您好!

您在心优雅社区注册账号时使用了这个邮箱,现在您需要点击下面的链接激活该账号:

%(protocol)s://%(domain)s 

如果链接无法点击,请将它完整复制到浏览器的地址栏进行访问.

链接有效期为%(expiration_days)s天,失效后需重新注册.

如果您并未进行过此操作,那么可能是有人误用了您的邮箱,请忽略此邮件."""%context
part = MIMEText(html,'html',_charset='UTF-8')
msg.attach(part)

username = 'postmaster@***org'
password = '****'
s = smtplib.SMTP('****.com:25')
s.login(username,password)
s.sendmail(fromEmail,toEmail,msg.as_string())
s.quit()

When I test it in the python IDLE,it work well. But,when I called this function to send email through my django project,UnicodeEncodeError let me crazy.

'ascii' codec can't encode characters in position 439-441: ordinal not in range(128)
Unicode error hint

The string that could not be encoded/decoded was: 亲爱的

Somebody can help?

It is really the sadness of beginners. When I have try many solutions from the SO or other websites, this error occured again and again. So I think this must be a fool question,then I turned to check if there are some spelling errors. YES,I mistakenly set the parameters for the MIMEText. So I changed the line of script to:

MIMEText(html,'html','utf8')

Now it's working.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM