使用drf django发送邮件

时间:2019-12-26 07:33:52

标签: django python-3.x django-rest-framework

我正在尝试从django drf发送邮件后发送邮件:

settings.py:

EMAIL_BACKEND = 'django.core.mail.backends.smtp.EmailBackend'
EMAIL_USE_TLS = True
EMAIL_HOST = 'smtp.gmail.com'
EMAIL_PORT = 587
EMAIL_HOST_USER = 'mymail@gmail.com'
EMAIL_HOST_PASSWORD = 'password'

serializers.py:

class RegisterSerializer(serializers.ModelSerializer):

      password = serializers.CharField(write_only=True)

      def create(self, validated_data):
          user = UserModel.objects.create(email=validated_data['email'])
          user.set_password(validated_data['password'])
          user.save()
          to_mail = user.email
          send_mail('Subject here','Here is the message.','myemail@gmail.com',['to_mail',],fail_silently=False,)
          return user
     class Meta:
           model = UserModel       
           fields = ( "id", "email", "password", )

我收到此错误:

SMTPRecipientsRefused at /api/registration/

{'=?utf-8?q?to=5Fmail?=': (553, b'5.1.3 The recipient address <=?utf-8?q?to=5Fmail?=> is not a valid RFC-5321\n5.1.3 address. u2sm31792629pgc.19 - gsmtp')}

我什至试图将邮件发送到其他邮件,但我仍然收到此错误

1 个答案:

答案 0 :(得分:1)

确保启用IMAP和/或POP3。如果启用IMAP或POP3后仍然遇到相同的错误,请尝试删除email_backend来尝试代码。

#EMAIL_BACKEND = 'django.core.mail.backends.smtp.EmailBackend'
EMAIL_USE_TLS = True
EMAIL_HOST = 'smtp.gmail.com'
EMAIL_PORT = 587
EMAIL_HOST_USER = 'mymail@gmail.com'
EMAIL_HOST_PASSWORD = 'password'