当尝试使用django.core.mail.backends.smtp.EmailBackend
发送电子邮件时,看起来ssl证书有问题。
Settings.py
EMAIL_HOST = 'smtp.gmail.com'
EMAIL_HOST_USER = 'email@gmail.com'
EMAIL_HOST_PASSWORD = 'password'
EMAIL_PORT = 587
EMAIL_BACKEND = 'django.core.mail.backends.smtp.EmailBackend'
EMAIL_USE_TLS = True
EMAIL_SSL_CERTFILE = certifi.where()
EMAIL_SSL_CA_BUNDLE = certifi.where()
密码是我在Google帐户中创建的应用程序密码。我甚至尝试使用第三方服务,如Elastic Email和SendGrid,但它仍然给我一个错误。删除EMAIL_SSL_CERTFILE
和EMAIL_SSL_CA_BUNDLE
将给予(_ssl.c:997)错误。
views.py
@api_view(["POST"])
def signupUser(request):
serializer = UserSerializer(data=request.data)
if serializer.is_valid():
serializer.save()
return Response(serializer.data)
else:
return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST)
Serializers.py
import random
from user_api.models import CustomUser
from django.contrib.auth.hashers import make_password
from django.core.mail import EmailMessage
from django.core.mail import send_mail
from rest_framework import serializers
class UserSerializer(serializers.ModelSerializer):
class Meta:
model = CustomUser
fields = ['username', 'email', 'password', 'profile_image', 'api_key']
extra_kwargs = {'password': {'write_only': True}, 'id': {'read_only': True}}
def update(self, instance, validated_data):
instance.username = validated_data['username']
instance.email = validated_data['email']
instance.api_key = validated_data['api_key']
instance.profile_image = validated_data['profile_image']
instance.save()
return instance
def create(self, validated_data):
verification_code = random.randint(100000, 999999)
user = CustomUser.objects.create(username=validated_data['username'],email=validated_data['email'], password=make_password(validated_data['password']), verification_code=verification_code)
user.set_password(validated_data['password'])
user.save()
email = EmailMessage(
'Hello',
f'This is your verification code : {verification_code}',
'email@gmail.com',
[validated_data['email']]
)
email.fail_silently=False
email.send()
return user
我也试过将EMAIL_BACKEND
切换到django.core.mail.backends.console.EmailBackend
。它工作得很好,我看到电子邮件被登录在控制台。
1条答案
按热度按时间eivnm1vs1#
这可能与使用
TLS
而不是SSL
有关,或者可能是由于SSL
证书的错误处理引起的。首先,我们尝试使用
TLS
,将EMAIL_USE_TLS
设置更改为False
,并将EMAIL_USE_SSL
设置为True
。另外,将EMAIL_PORT
更改为465或者我们可以删除
EMAIL_SSL_CERTFILE
和EMAIL_SSL_CA_BUNDLE
,您的电子邮件设置应该是这样的: