How to send emails with Django for Password Reset? - python

I am trying to send password change link to an email address which a user will type. I typed my email but it is not sending me any link. How to resolve this issue?
urls
urlpatterns = [
path('password_reset/',auth_views.PasswordResetView.as_view
(template_name='users/password_reset.html'),
name='password_reset'),
path('password_reset_done/',auth_views.PasswordResetDoneView.as_view
(template_name='users/password_reset_done.html'),
name='password_reset_done'),
path('password_reset_confirm/',auth_views.PasswordResetConfirmView.as_view
(template_name='users/password_reset_confirm.html'),
name='password_reset_confirm')]
settings.py
EMAIL_BACKEND = 'django.core.mail.backends.smtp.EmailBackend'
EMAIL_HOST = 'smtp.gmail.com'
EMAIL_PORT = 587
EMAIL_USE_TLS = True
EMAIL_HOST_USER = os.environ.get('EMAIL_USER')
EMAIL_HOST_PASSWORD = os.environ.get('EMAIL_PASS')

I use these as my urls. The main difference I spot with yours right away is with password-reset-confirm. Make sure your passing the token.
from django.contrib.auth import views as auth_views
path('password-reset/', auth_views.PasswordResetView.as_view(template_name='users/password_reset.html'), name='password_reset'),
path('password-reset-confirm/<uidb64>/<token>/', auth_views.PasswordResetConfirmView.as_view(template_name='users/password_reset_confirm.html'), name='password_reset_confirm'),
path('password-reset/done/', auth_views.PasswordResetDoneView.as_view(template_name='users/password_reset_done.html'), name='password_reset_done'),
path('password-reset-complete/', auth_views.PasswordResetCompleteView.as_view(template_name='users/password_reset_complete.html'),
My settings look like this
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')
Also please note that you need to set up a g-mail account to allow Django or any other app to access it, it doesn't work automatically. The password you receive after doing this IS NOT the same as the password you normally log in with. It may be this that is causing you issues.
As I saw you are missing the tokens in your password-reset-confirm URL it is perhaps also the problem that your don't have a token generator.
from django.contrib.auth.tokens import PasswordResetTokenGenerator
from django.utils 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()
I created this in a file named token_generator.py.

Related

Reset password email from django doesn't appear in my mailbox

Scenario:
In my django application, admin should create users using 'username' and 'email', 'password' will be generated auto .Welcome email will be sent to users with redirect link to reset password.
Issue:
after entering email for reset password the app should send email with link to confirm reset password. THE PROBLEM is the email it never show in user "inbox" but i can find it in app "outbox mails"
How can i make it appear in user mailbox?
Any Help or idea?
I'm using:
-Python3
-Django4
-enable two factor authentication(2FA) for Google account
Settings.py:
#SMTP Config
EMAIL_BACKEND = 'django.core.mail.backends.smtp.EmailBackend'
EMAIL_HOST = 'smtp.gmail.com'
EMAIL_PORT = '587'
EMAIL_USE_TLS = True
EMAIL_HOST_USER = "webapp#app.com"
DEFAULT_FROM_EMAIL = "MyApp <no-reply#app.com>"
EMAIL_HOST_PASSWORD = "******"
APP/URLS:
urlpatterns = [
path('',views.login_user, name ='login'), #login fonction path
path ('user_logout',views.user_logout, name = 'logout'), #logout function path
path('dashboard/', views.dashboard, name='dashboard'),# dashoard view path
path ('daily',views.DailyView, name = 'dailydashboard'),#daily view depath
path ('monthly',views.MonthlyView, name = 'Monthlydashboard'),#monthly view path
path ('yearly',views.YearlyView, name = 'Yearlydashboard'), #yearly view path
path("reset_password/", auth_views.PasswordResetView.as_view(template_name="password/password_reset.html"), name="reset_password"),
path('password_reset_done/', auth_views.PasswordResetDoneView.as_view(template_name="password/password_reset_done.html"), name='password_reset_done'),
path('reset/<uidb64>/<token>/', auth_views.PasswordResetConfirmView.as_view(template_name="password/password_reset_confirm.html"), name='password_reset_confirm'),
path('password_reset_complete/', auth_views.PasswordResetCompleteView.as_view(template_name='password/password_reset_complete.html'), name='password_reset_complete'),
]

TemplateDoesNotExist at /account/password_reset_confirm/MQ/set-password/ registrationpassword_reset_confirm.html

I`m using the Django authentication system to reset the user password. I create an app named account, in which I add the following codes in the urls.py modules:
from django.urls import path, include
from django.contrib.auth import views as auth_views
from . import views
urlpatterns=[
path('password_reset/',
auth_views.PasswordResetView.as_view(),
name='password_reset'),
path('password_reset/done/',
auth_views.PasswordResetDoneView.as_view(),
name='password_reset_done'),
path('password_reset_confirm/<uidb64>/<token>/',
auth_views.PasswordResetConfirmView.as_view(
template_name='registration/password_reset_confirm.html'),
name='password_reset_confirm'),
path('reset/done/',
auth_views.PasswordResetCompleteView.as_view(),
name='password_reset_complete'),
]
I create all the templated needed in the app`s template/registration repository:
password_reset_form.html, password_reset_done.html, password_reset_confirm.html, password_reset_complete.html,
And I also add the email setting to my project:
EMAIL_BACKEND = 'django.core.mail.backends.smtp.EmailBackend'
EMAIL_HOST = 'smtp.gmail.com'
EMAIL_HOST_USER = '********'
EMAIL_HOST_PASSWORD = '**********'
EMAIL_PORT = 587
EMAIL_USE_TLS = True
I run the server, on the password reset page I enter the email that the user is verified, after that, I received the password reset link in my inbox, but When I click it then the TemplateDoesNotExist exception occurs.
I read the Django Documentation of Using the Django authentication system at https://docs.djangoproject.com/en/3.1/topics/auth/default/#built-in-auth-views.
Then I change the template name password_reset_confirm.html to password-reset-confirm.html, and somehow it works!
Is 'registration' the name of the folder where you put all of your templates files? if it is, all of the as_view() should have template_name inside them e.g auth_views.PasswordResetView.as_view(template_name='registration/password_reset_form.html'), name='password_reset')

Sending mail though django

In my project, I tried to allow users to change and reset password. But can't figure out why this mail configuration isn't working. Actually, it doesn't send mail to the user. But showing e-mail has been sent on API.
Here is my code:
settings.py
REST_SESSION_LOGIN = True
EMAIL_BACKEND = 'django.core.mail.backends.console.EmailBackend'
SITE_ID = 1
ACCOUNT_EMAIL_REQUIRED = False
ACCOUNT_AUTHENTICATION_METHOD = 'username'
ACCOUNT_EMAIL_VERIFICATION = 'optional'
#mail config
EMAIL_HOST = 'smtp.gmail.net'
EMAIL_PORT = 587
EMAIL_HOST_USER = 'mygmail#gmail.com'
EMAIL_HOST_PASSWORD = '************' #gmail app password
EMAIL_USE_TLS = True
urls.py
urlpatterns = [
path('admin/', admin.site.urls),
path('authentication/', include('dj_rest_auth.urls')),
path('authentication/registration/', include('dj_rest_auth.registration.urls')),
path('api/', include('articles.api.urls')),
re_path(r'^authentication/password/reset/confirm/(?P<uidb64>[0-9A-Za-z_\-]+)/(?P<token>[0-9A-Za-z]{1,13}-[0-9A-Za-z]{1,20})/$', PasswordResetConfirmView.as_view(), name='password_reset_confirm')
]
And in terminal at from it shows webmaster#localhost. But why it isn't showing EMAIL_HOST_USER e-mail.
Subject: Password reset on example.com
From: webmaster#localhost
To: gicof53256#tdcryo.com
Date: Sun, 29 Nov 2020 08:14:16
When you have mentioned EMAIL_BACKEND = 'django.core.mail.backends.console.EmailBackend' this will mock the email, but not actually send it. To actually send it, replace it with the below settings.
Also, it's better to store the credentials in environment variables. I am attaching the code snippet that will do the job.
EMAIL_HOST_PASSWORD = os.environ.get('EMAIL_HOST_PASSWORD')
EMAIL_HOST_USER = os.environ.get('EMAIL_HOST_USER')
EMAIL_HOST = os.environ.get('EMAIL_HOST')
EMAIL_USE_TLS = True
EMAIL_USE_SSL = False
EMAIL_PORT = 587

django docs email is not activated after click on email confirmation link in Django mail backend

I created the Django email backend for active the email during the registration. But in my case When I register the account and confirmation email is sent on my email and after click on the confirmation link then it's not activate the user's account and link is not redirected on login page.
setting.py
EMAIL_BACKEND = 'django.core.mail.backends.smtp.EmailBackend'
EMAIL_HOST = 'smtp.gmail.com'
EMAIL_USE_TLS = True
EMAIL_PORT = 587
EMAIL_HOST_USER = 'your_mail#gmail.com'
EMAIL_HOST_PASSWORD = 'XXXXXXXXXX'
ACCOUNT_EMAIL_VERIFICATION = 'mandatory'
ACCOUNT_EMAIL_REQUIRED = True
ACCOUNT_AUTHENTICATION_METHOD = "USERNAME"
ACCOUNT_CONFIRM_EMAIL_ON_GET = True
ACCOUNT_EMAIL_CONFIRMATION_ANONYMOUS_REDIRECT_URL = reverse_lazy('account_confirm_complete')
ACCOUNT_EMAIL_CONFIRMATION_AUTHENTICATED_REDIRECT_URL = reverse_lazy('account_confirm_complete')
urls.py
urlpatterns = [
url(r'^user_reg/registration/account-email-verification-sent/', email_view.null_view, name='account_email_verification_sent'),
url(r'^user_reg/registration/account-confirm-email/(?P<key>[-:\w]+)/$', VerifyEmailView.as_view(), name='account_confirm_email'),
url(r'^user_reg/registration/complete/$', email_view.complete_view, name='account_confirm_complete'),
url(r'^user_reg/password-reset/confirm/(?P<uidb64>[0-9A-Za-z_\-]+)/(?P<token>[0-9A-Za-z]{1,13}-[0-9A-Za-z]{1,20})/$', email_view.null_view, name='password_reset_confirm'),
path('admin/', admin.site.urls),
path('user_reg/', include('users.urls', namespace="users")),
path('user_reg/registration/', include('rest_auth.registration.urls')),
] + static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)
And below the email message
Greeting from example.com!
You're receiving this e-mail because user usertest has given yours as an e-mail address to connect their account via API.
To confirm this is correct, go to http://127.0.0.1:8000/user_reg/registration/account-confirm-email/Mjg:1jSeJC:4btJkSnHSxYN7w5CITEPydcG9cA/
Thank you from example.com!
example.com
Where is the problem and how can I solve this?.
Please help me. Thank you!

How to change settings.py variables using admin?

I'm working on a "contact us" page in Django. I want to allow admin to change their smtp,name,password and port in django admin.
So there is a table admin_contact which can be modified via admin page. The problem is that I don't know how to set EMAIL_HOST,EMAIL_PORT,EMAIL_HOST_USER and
EMAIL_HOST_PASSWORD inside settings.py (using model admin_contact) which I have to set to be able to use send_mail method in views.py.
Is there a way to do this?
This is force solution but it solved my problem.
Generate a file (email_config.py) with your Information (Email, Password, smtp, etc) from a Form.
email_config.py
CONFIG_HOST = "smtp.gmail.com"
CONFIG_EMAIL = "mail#gmail.com"
CONFIG_PASS = "******"
CONFIG_PORT = "587"
Import email_config.py from you setting.
setting.py
from email_config import CONFIG_HOST, CONFIG_EMAIL, CONFIG_PASS, CONFIG_PORT
...
EMAIL_BACKEND = 'django.core.mail.backends.smtp.EmailBackend'
EMAIL_USE_TLS = True
# G-mail
EMAIL_HOST = CONFIG_HOST
EMAIL_HOST_USER = CUSTOM_EMAIL
EMAIL_HOST_PASSWORD = CONFIG_PASS
EMAIL_PORT = CONFIG_PORT
EMAIL_FROM_EMAIL = EMAIL_HOST_USER
DEFAULT_FROM_EMAIL = EMAIL_HOST_USER
SERVER_EMAIL = EMAIL_HOST_USER
Test
> python manage.py shell
> from django.core.mail import EmailMessage
> msg = EmailMessage("Hi, man","This is a test message",to=["juan#gmail.com"])
> msg.send()
1
Apache and mod_wgsi need restart after change information

Categories

Resources