Is it a django's bug or something mistaken,when I can't encode chinese characters in django environment?

20 views
Skip to first unread message

jie.l...@gmail.com

unread,
Apr 28, 2014, 11:00:03 PM4/28/14
to django...@googlegroups.com

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 in my django project,or run it in "manage.py shell",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: 亲爱的

Simon Charette

unread,
Apr 29, 2014, 1:48:23 AM4/29/14
to django...@googlegroups.com
Maybe those API's expect you to pass them bytes and not text.

Did you try encoding your subject and your body as 'utf-8' bytes (using .encode('utf-8'))?

Simon
Reply all
Reply to author
Forward
0 new messages