django用QQ邮箱发送SMTP邮件踩坑笔记
介绍
django发送邮件是比较常见的需求,国内比较普遍使用的QQ的SMTP发送邮件服务
但是网上教程还是挺多坑,尝试半天终于成功了,这里记录一下
QQ邮箱配置
QQ邮箱设置里点击管理服务
生成授权码
点击查看配置SMTP和IMAP方法,其实下面讲不对
具体配置
EMAIL_BACKEND = 'django.core.mail.backends.smtp.EmailBackend'
EMAIL_HOST = 'smtp.qq.com'
EMAIL_PORT = 25 # 关键这个端口,必须写25,按官网的端口都没用
EMAIL_USE_TLS = False
EMAIL_HOST_USER = '' # 你的邮箱地址
EMAIL_HOST_PASSWORD = '' # 你的授权码
发送邮件代码
from django.core.mail import send_mail
email = serializer.validated_data['email']
code = ''.join(random.choices(string.ascii_uppercase + string.digits, k=4))
send_result =send_mail(
'你的邮箱验证码',
f'你的邮箱验证码是: {code}',
settings.EMAIL_HOST_USER, # 发件人邮箱
,
fail_silently=False,
)
if send_result == 1:
# 处理你的业务逻辑,例如保存验证码到数据库
EmailVerifyCode.objects.create(email=email, code=code)
return Response({"message": "Captcha and email are valid. Email sent successfully."},
status=status.HTTP_200_OK)
else:
return Response({"message": "Failed to send email. Please try again later."},
status=status.HTTP_500_INTERNAL_SERVER_ERROR)