djangodjango-viewsdjango-formsdjango-templatesgmail

How can I send a reset password email on Django?


During the process of creating my first website using Django framework, I encountered a little problem that I couldn't found a solution yet. So, when an user wants to reset his or her password, i'd like to send to him/her a reset mail. So far, I have this:

urls.py

from django.contrib.auth import views as auth_views

......    
path('password-reset/', auth_views.PasswordResetView.as_view(template_name='registration/password_reset_form.html'),
         name='password_reset'),
    path('password-reset-confirm/<uidb64>/<token>/',
         auth_views.PasswordResetConfirmView.as_view(template_name='registration/password_reset_confirm.html'),
         name='password_reset_confirm'),
    path('password-reset/done/',
         auth_views.PasswordResetDoneView.as_view(template_name='registration/password_reset_done.html'),
         name='password_reset_done'),
    path('password-reset-complete/',
         auth_views.PasswordResetCompleteView.as_view(template_name='registration/password_reset_complete.html')),
....

settings.py

EMAIL_BACKEND = "django.core.mail.backends.console.EmailBackend"
EMAIL_HOST = 'smtp.gmail.com'
EMAIL_POST = 587
EMAIL_USE_TLS = True
EMAIL_HOST_USER = os.environ.get('traces_email')
EMAIL_HOST_PASSWORD = os.environ.get('traces_email_password')

I created a token generator for my link: token_generator.py

from django.contrib.auth.tokens import PasswordResetTokenGenerator
import six


class TokenGenerator(PasswordResetTokenGenerator):
    def _make_hash_value(self, user, timestamp):
        return (
            six.text_type(user.pk) + six.text_type(timestamp) + six.text_type(user.is_active)
        )
account_activation_token = TokenGenerator()

When I go through the reset flow, it does not send any email. It is still sent to my terminal. Can somebody help me with this issue? Thank you so much for your time!


Solution

  • This setting

    EMAIL_BACKEND = "django.core.mail.backends.console.EmailBackend"
    

    tells django to send the message to your terminal. To actually send an email, you need to use

    EMAIL_BACKEND = "django.core.mail.backends.smtp.EmailBackend"
    

    This is described in the Django Docs.