Django project is not sending confirmation email

26 Views Asked by At

So, i'm trying to create a user registration project with email confirmation

the user will need to confirm its email first, then be able to login

in settings.py I have:

DEBUG = True
EMAIL_HOST = 'smtp.gmail.com'
EMAIL_HOST_USER = 'my email here'
EMAIL_HOST_PASSWORD = 'my pw here'
EMAIL_PORT = 587
EMAIL_USE_TLS = True
EMAIL_BACKEND = 'django.core.mail.backends.smtp.EmailBackend'

and in views.py

def createuser(request):
    form = MyUserCreationForm()

    if request.method == 'POST':
        form = MyUserCreationForm(request.POST)
        if form.is_valid():     
            code = User.objects.make_random_password(length=6,allowed_chars='1234567890')

            user = form.save(commit=False)
            user.is_active = False 
            user.save()
            # if User.is_email_confirmed == False:

            user.code = code
            user.save()
            
            subject = 'Confirm your email' 
            confirmation_code = code
            message = f'Confirm your email with this code: {confirmation_code}'
            from_email = '...'
            to_email = request.user.email
            email = EmailMessage(subject, message, to=[to_email])
            email.send()

            # else:
            #     user = form.save(commit=False)
            #     user.username = user.username.lower()
            #     user.save()
            #     login(request,user)
            #     return redirect('home')
        else:
            messages.error(request,'An error occured during your registration')
    context = {'form':form}
    return render(request, 'signup.html', context)

The user is being saved but absolutely nothing is send in any email

then I tried


email = EmailMessage(subject, message, to=[to_email])
email.send()

instead of


send_mail(subject,message,from_email,[to_email])
            return redirect('emailconfirm.html')

nothing solved.

1

There are 1 best solutions below

0
Sahil On

views.py

from django.core.mail import EmailMessage


def abc(request):
    message = request.POST.get('message')
    email =  request.POST.get('email')
     
    email = EmailMessage(body= message, to=[email])
    email.send()


   

setting.py

EMAIL_BACKEND = 'django.core.mail.backends.smtp.EmailBackend'  # Or your preferred backend
EMAIL_HOST = 'smtp.gmail.com'  # Example for Gmail
EMAIL_PORT = 587
EMAIL_USE_TLS = True
EMAIL_HOST_USER = 'sahsdadasdsadgmail.com'
EMAIL_HOST_PASSWORD = ddco usds apffd fvsx'
DEFAULT_FROM_EMAIL = 'sahsdadasdsadgmail.com'