I'm trying to send a confirmation email every time a user signs up for my service. I followed tutorials but while the user is getting signed up, the email is not being sent.
This is my views.py
def signup_view(request):
if request.method == "POST":
first_name= request.POST.get('first_name')
last_name = request.POST.get('last_name')
email = request.POST.get('email', 'default user')
phone = request.POST.get('phone')
password1= request.POST.get('password1')
password2= request.POST.get('password2')
userHash= email.replace('@','')
# userHash =~ s/'@'//g
#new =User.objects.filter(username = userHash)
if password1 != password2:
return render(request, 'signup.html',{'error_message': ' Passwords Different'})
else:
user = User.objects.create_user((userHash, password1))
user.save()
login(request, user)
current_site = get_current_site(request)
user = request.user
email = request.user.email
subject = "Verify Email"
message = render_to_string('account/verify_email_message.html', {
'user': user,
'domain': current_site.domain,
'uid':urlsafe_base64_encode(force_bytes(user.pk)),
'token':account_activation_token.make_token(user),
})
email = EmailMessage(
subject, message, to=[email]
)
email.send()
return HttpResponse("Please Confirm your email address to complete the registration") and render(request,'account/landing.html')
else:
form = CreateUserForm()
context = {
'form': form
}
return render(request, 'account/signup.html', context)
def activate(request, uidb64, token):
try:
uid = force_str(urlsafe_base64_decode(uidb64))
user = User.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()
return HttpResponse("Thank you for this confirmation") and redirect('account/index.html')
else:
messages.warning(request, 'The link is invalid.')
return render(request, 'account/index.html')
def home(request):
return render(request, 'account/index.html')
This is my 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 = "myjarwiz2024@gmail.com" # - GMAIL email address
EMAIL_HOST_PASSWORD = 'redacted' # - APP password
DEFAULT_FROM_EMAIL = 'Jarwiz myjarwiz2024@gmail.com' # - GMAIL email address
While all the redirects are happening, the email isn't being sent.
I tried doing it using other tutorials, changed views and followed instructions from stack overflow to solve errors but I'm unable to do this.
I found out what I did wrong.
user = request.user
email = request.user.email
I removed the above two lines and the email was sent.