如何使用django发送非英语单词(中文)电子邮件

时间:2010-12-15 06:08:24

标签: python django email non-english

如果我使用中文单词主题:

subject = u'邮件标题'

将显示错误:

UnicodeDecodeError at /account/login_view/

'utf8' codec can't decode bytes in position 0-1: invalid data

我该怎么办呢,

感谢

更新

def register_view(request):
    if request.method == 'POST':
        form = SignupForm(request.POST)
        if form.is_valid():
            # Process the data in form.cleaned_data
            # ...
            username = form.cleaned_data['username']
            password = form.cleaned_data['password']
            email = form.cleaned_data['email']
            user = User.objects.create_user(username, email, password)

            send_html_mail(subject, html_content, [email])
            if user is not None:
                user.save()
                #return HttpResponse(simplejson.dumps({'msg':'ok'}))
                return HttpResponseRedirect("/")
            else:
                return HttpResponseRedirect("/account/register_view") 
    else:
        form = SignupForm() # An unbound form

    return render_to_response('accounts/register_view.html',{'form': form,})

def login_view(request): 
    if request.method == 'POST': 
        form = LoginForm(request.POST) 
        if form.is_valid():
            username = form.cleaned_data['username']
            password = form.cleaned_data['password']
            user = authenticate(username=username, password=password)  
            if user is not None:  
                if user.is_active:
                   login(request, user)
                   return HttpResponseRedirect("/")
                else:
                   return HttpResponse('user is not active')
            else:
                #return HttpResponseRedirect("/account/login_submit") 
                return HttpResponse('No this username . and <a href="/">return to homepage</a>')
    else:
        form = LoginForm() # An unbound form

    return render_to_response('accounts/login_view.html',{'form': form,})

2 个答案:

答案 0 :(得分:2)

你是如何发送主题的。您应该在发送之前将其编码为utf-8。

subject.encode('utf-8')

import codecs
subject = codecs.utf_8_encode(subject)

然后将其发送到您的视图。

答案 1 :(得分:0)

现在好了:

我使用Programmer’s Notepad 2Encoding pyhtml文件,该文件包含中文字。

alt text