Home > OS >  Avoid temp emails using Django
Avoid temp emails using Django

Time:09-17

I want to block temp emails and ensure the user can register only if the email is real (like Gmail, Outlook, Yahoo).

forms.py

class SginupForm(UserCreationForm):
    class Meta:
        model = User
        fields =('username', 'first_name','last_name','email','password1','password2' )

views.py

@unauthenticated_user
def signup_form(request):
    if request.method == 'POST':
        form=SginupForm(request.POST)
        if form.is_valid():
            user=form.save()
            send_action_email(user,request)
            messages.add_message(request, messages.SUCCESS,
                                 'we have sent ur activation link')
            return redirect('core:login')
   
    else:
        form=SginupForm()
    return render(request,'user/sign-up.html',{'form':form})

CodePudding user response:

There isn't an automatic way to know if an email is a temporary one or not. So I would just use a whitelist. Just make sure you include all the most popular email providers (do a Google search for that).

Create a list of emails. For good practice, this should be as a constant at the top of your views.py file.

ALLOWED_EMAILS = ["gmail.com", "outlook.com", "yahoo.com"]

Then when your user submits a Signup Form, simply validate that the email address ends with any of these.

The below condition checks if the email does not end with any of the whitelisted emails. Add it right after the user submits the form. Add your own custom message and redirect logic.

email = form.cleaned_data.get("email")
if not any(email.endswith(e) for e in ALLOWED_EMAILS):
    # Add a failure message to the request.
    # Redirect back to the login page.
  • Related