尝试发送电子邮件时如何修复 Django 中的编码错误

How to fix the encode error in Django while trying to send an e-mail

我正在尝试向 Django 中的新注册帐户发送验证电子邮件,但我收到一个编码错误,我不知道如何修复,请帮助我修复它,这样我就可以成功验证帐号

aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa

if DEBUG:
        EMAIL_HOST = 'smtp.gmail.com'
        EMAIL_PORT = 587
        EMAIL_USE_TLS = True
        EMAIL_HOST_USER = 'jamelaumn@gmail.com'
        EMAIL_HOST_PASSWORD = xxxxx  # important
    else:
        EMAIL_BACKEND = 'django.core.mail.backends.console.EmailBackend'

我的urls.py:

path('register/', views.account_register, name='register'),

我的views.py:

from django.template.loader import render_to_string
from django.utils.encoding import force_bytes
from django.utils.http import urlsafe_base64_decode, urlsafe_base64_encode
from django.core.mail import EmailMessage
from django.conf import settings
from django.template.loader import render_to_string

def account_register(request):

    if request.user.is_authenticated:
        return redirect('account:dashboard')

    if request.method == 'POST':
        registerForm = RegistrationForm(request.POST)
        if registerForm.is_valid():
            user = registerForm.save(commit=False)
            user.email = registerForm.cleaned_data['email']
            user.set_password(registerForm.cleaned_data['password'])
            user.is_active = False
            email_to = user.email
            user.save()
            email_subject = 'Ative sua conta'
            current_site = get_current_site(request)
            message = render_to_string('account/registration/account_activation_email.html', {
                'user': user,
                'domain': current_site.domain,
                'uid': urlsafe_base64_encode(force_bytes(user.pk)),
                'token': account_activation_token.make_token(user),
            })

            email_body = message

            email = EmailMessage(
                email_subject,
                email_body,
                settings.EMAIL_HOST_USER, [email_to])
            email.send()
            return HttpResponse('registered succesfully and activation sent')
    else:
        registerForm = RegistrationForm()
    return render(request, 'account/registration/register.html', {'form': registerForm})


def account_activate(request, uidb64, token):
    try:
        uid = urlsafe_base64_decode(uidb64)
        user = UserBase.objects.get(pk=uid)
    except(TypeError, ValueError, OverflowError, user.DoesNotExist):
        user = None
    if user is not None and account_activation_token.check_token(user, token):
        user.is_active = True
        user.save()
        login(request, user)
        return redirect('account:dashboard')
    else:
        return render(request, 'account/registration/activation_invalid.html')

控制台出错

C:\Users\kayna\AppData\Local\Programs\Python\Python310\lib\smtplib.py", line 652, in auth authobject(challenge).encode('ascii'), eol='') AttributeError: 'int' object has no attribute 'encode' [25/May/2022 16:49:50] "POST /django-store-account/register/ HTTP/1.1" 500 92726

整个控制台错误编码:

Internal Server Error: /django-store-account/register/
Traceback (most recent call last):
  File "C:\Users\kayna\OneDrive\Área de Trabalho\ebrelease\venv\lib\site-packages\django\core\handlers\exception.py", line 55, in inner
    response = get_response(request)
  File "C:\Users\kayna\OneDrive\Área de Trabalho\ebrelease\venv\lib\site-packages\django\core\handlers\base.py", 
line 197, in _get_response
    response = wrapped_callback(request, *callback_args, **callback_kwargs)
  File "C:\Users\kayna\OneDrive\Área de Trabalho\ebrelease\account\views.py", line 134, in account_register      
    email.send()
  File "C:\Users\kayna\OneDrive\Área de Trabalho\ebrelease\venv\lib\site-packages\django\core\mail\message.py", line 298, in send
    return self.get_connection(fail_silently).send_messages([self])
  File "C:\Users\kayna\OneDrive\Área de Trabalho\ebrelease\venv\lib\site-packages\django\core\mail\backends\smtp.py", line 124, in send_messages
    new_conn_created = self.open()
  File "C:\Users\kayna\OneDrive\Área de Trabalho\ebrelease\venv\lib\site-packages\django\core\mail\backends\smtp.py", line 91, in open
    self.connection.login(self.username, self.password)
  File "C:\Users\kayna\AppData\Local\Programs\Python\Python310\lib\smtplib.py", line 739, in login
    (code, resp) = self.auth(
  File "C:\Users\kayna\AppData\Local\Programs\Python\Python310\lib\smtplib.py", line 652, in auth
    authobject(challenge).encode('ascii'), eol='')
AttributeError: 'int' object has no attribute 'encode'
[25/May/2022 21:24:58] "POST /django-store-account/register/ HTTP/1.1" 500 92687

与 send_mail:

由于错误是由 built-in smtp python 库引发的,这意味着您传递了错误的编码类型。根据文档和错误消息,它需要二进制,但如果收到字符串,它会尝试转换为 ASCII。

似乎在某个地方你传递了一个 int ,而不是追逐编码,因为你没有使用 EmailMessage 的任何高级功能,你应该能够只使用实用程序Django提供的方法send_email

所以,这应该做到了

    mail.send_mail(subject = email_subject, message = message, 
                   from_email = settings.EMAIL_HOST_USER, [email_to], 
                   html_message=html_message)

应该不需要编码,您可以像往常一样在模板中使用上下文值,然后通过条带化生成 text/plain 消息 HTML 与 strip_tags ,即 message = strip_tags(html_message)