Is there any way to know if an email address exists before creating a user in Django?
I have a RegistrationSerializer in which I crate a user with is_verfied=False
. And I wanted to prevent bad intended users to create fake accounts. Even if they can't login due to the email verification step, it would still be a headache if someone just posted a lot of fake users.
class RegistrationSerializer(serializers.ModelSerializer):
class Meta:
model = User
fields = ('email', 'password', 'cpf', 'is_active')
extra_kwargs = {
'password': {'write_only': True}
}
def validate(self, data):
return data
def create(self, validated_data):
user = User.objects.create_user(**validated_data)
token = generate_email_verification_token.make_token(user)
verification_url = f"{os.environ.get('FRONTEND_URL')}/verify-email?uid={user.id}&token={token}"
subject = "..."
plain_message = (
"...{verification_url}..."
)
html_message = f"""
...{verification_url}...
"""
send_mail(
subject,
plain_message,
settings.DEFAULT_FROM_EMAIL,
[user.email],
html_message=html_message,
fail_silently=False,
)
return user
And I tried to except send_email
to delete the created user if there was any problem (e.g. it wasn't able to send the email because that email box does not exist) while trying to send the email, but nothing worked:
try:
send_mail(
subject,
plain_message,
settings.DEFAULT_FROM_EMAIL,
[user.email],
html_message=html_message,
fail_silently=False,
)
except BadHeaderError: # If mail's Subject is not properly formatted.
print('Invalid header found.')
user.delete()
raise ValidationError
except SMTPException as e: # It will catch other errors related to SMTP.
user.delete()
print('There was an error sending an email.'+ e)
raise ValidationError
except: # It will catch All other possible errors.
user.delete()
print("Mail Sending Failed!")
raise ValidationError
So, is there any way that I can prevent bad intended users from creating fake email accounts?