I am following this tutorial the aim to verify email after users register to the system. here is the code.
serializers.py
class RegisterSerializer(serializers.ModelSerializer):
password = serializers.CharField(
max_length=68, min_length=6, write_only=True)
default_error_messages = {
'username': 'The username should only contain alphanumeric characters'}
class Meta:
model = User
fields = ['email', 'username', 'password']
def validate(self, attrs):
email = attrs.get('email', '')
username = attrs.get('username', '')
if not username.isalnum():
raise serializers.ValidationError(
self.default_error_messages)
return attrs
def create(self, validated_data):
return User.objects.create_user(**validated_data)
my view.py
class RegisterView(generics.GenericAPIView):
serializer_class = RegisterSerializer
def post(self, request):
user = request.data
serializer = self.serializer_class(data=user)
serializer.is_valid(raise_exception=True)
serializer.save()
user_data = serializer.data
user = User.objects.get(email=user_data['email'])
token = RefreshToken.for_user(user).access_token
current_site = get_current_site(request).domain
relativeLink = reverse('email-verify')
absurl = 'http://' + current_site + relativeLink + "?token=" + str(token)
email_body = 'Hi ' + user.username + \
' Use the link below to verify your email \n' + absurl
data = {
'email_body': email_body ,
'to_email': user.email ,
'email_subject' : 'Verify your email'
}
Util.send_email(data)
return Response(user_data , status=status.HTTP_201_CREATED)
my utils.py
class EmailThread(threading.Thread):
def __init__(self, email):
self.email = email
threading.Thread.__init__(self)
def run(self):
self.email.send()
class Util:
@staticmethod
def send_email(data):
email = EmailMessage(
subject=data['email_subject'], body=data['email_body'] , to=[data['to_email']])
EmailThread(email).start()
and the settings.py
EMAIL_USE_TLS = True
EMAIL_HOSTS = "smtp.gmail.com"
EMAIL_PORT = 587
EMAIL_HOST_USER = "talibdaryabi@gmail.com"
EMAIL_HOST_PASSWORD = "**********"
when I test the URL http://127.0.0.1:8000/auth/register/
by providing
{
"email":"talibacademic@gmail.com",
"username":"talibacademic",
"password":"aahg786ahg786"
}
I get the
{
"email": "talibacademic@gmail.com",
"username": "talibacademic"
}
which means the user was created but can't receive email.
can anyone help me with the issue, I also have allowed Less secure app access setting for talibdaryabi@gmail.com account.