通过Django发送电子邮件给我(_ssl.c:3895)错误

fykwrbwg  于 2023-06-25  发布在  Go
关注(0)|答案(1)|浏览(142)

当尝试使用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_CERTFILEEMAIL_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。它工作得很好,我看到电子邮件被登录在控制台。

eivnm1vs

eivnm1vs1#

这可能与使用TLS而不是SSL有关,或者可能是由于SSL证书的错误处理引起的。
首先,我们尝试使用TLS,将EMAIL_USE_TLS设置更改为False,并将EMAIL_USE_SSL设置为True。另外,将EMAIL_PORT更改为465
或者我们可以删除EMAIL_SSL_CERTFILEEMAIL_SSL_CA_BUNDLE,您的电子邮件设置应该是这样的:

EMAIL_HOST = 'smtp.gmail.com'
EMAIL_HOST_USER = 'email@gmail.com'
EMAIL_HOST_PASSWORD = 'password'
EMAIL_PORT = 465
EMAIL_USE_TLS = False
EMAIL_USE_SSL = True
EMAIL_BACKEND = 'django.core.mail.backends.smtp.EmailBackend'

相关问题