一.注册邮箱
可以使用QQ,新浪,163等等,每个邮箱端口可能不一样,这里以新浪为例,登录后修改设置中开启POP/SMTP服务如下:
二.setting中的配置
相应参数可以参考官网,常用如下:
EMAIL_BACKEND = 'django.core.mail.backends.smtp.EmailBackend' EMAIL_HOST = 'smtp.sina.com' EMAIL_PORT = 25 #邮箱用户名 EMAIL_HOST_USER = '***@sina.com' #邮箱密码 EMAIL_HOST_PASSWORD = 'password' EMAIL_USE_TLS = False #一般和用户名一样 EMAIL_FROM = '发送者'
注:端口可能不能用,如我遇到的问题是在本地测试能发送邮件,部署到服务器(阿里云centos7.0)上则总是超时,很头疼,查询了相关资料,如下:
服务器25端口被大量垃圾邮件充斥,严重影响广大用户正常使用。为了共同维护良好的网络环境,阿里云服务器不再提供25端口邮件服务,阿里云企业邮箱将80端口重定向到了25端,与直接调用25端的发信方式没有区别。如果是阿里云的邮箱,需要使用 80 端口发送邮件。然后需要再邮件设置里,把发送端口改为 465 或 80 端口进行发送,其他邮箱建议尝试使用465加密端口发送邮件,或与邮件发信提供商咨询是否还有其他smtp发信端口。
于是我尝试用465端口,还是不行,最后尝试587端口成功。
三.编写发送的代码
代码比较简单,可以根据自己的需要定制
# _*_ encoding:utf-8 _*_ __author__ = 'LYQ' __data__ = '2018/8/2 20:06' from random import Random from django.core.mail import send_mail from News_Contrl.settings import EMAIL_FROM def random_str(randomlength=8): str = '' chars = 'AaBbCcDdEeFfGgHhIiJjKkLlMmNnOoPpQqRrSsTtUuVvWwXxYyZz0123456789' length = len(chars) - 1 random = Random() for i in range(randomlength): str += chars[random.randint(0, length)] return str def send_register_email(email, send_type='register'): code = random_str(4) if send_type == 'register': email_title = 'CINS爬虫监控系统注册' email_body = '您的验证码为:{0},五分钟内注册有效,否则请从新获取'.format(code) send_status = send_mail(email_title, email_body, EMAIL_FROM, [email]) if send_status: return code,send_status elif send_type == 'forget': email_title = 'CINS爬虫监控系统密码找回' email_body = '请点击下面的链接找回你的账号:http://127.0.0.1:8000/reset/{0}'.format(code) send_status = send_mail(email_title, email_body, EMAIL_FROM, [email]) if send_status: return code, send_status, send_type elif send_type == 'update_email': email_title = 'CINS爬虫监控系统邮箱修改' email_body = '您的邮箱验证码为:{0}'.format(code) send_status = send_mail(email_title, email_body, EMAIL_FROM, [email]) if send_status: return code, send_status, send_type if __name__ == "__main__": send_register_email("1508414512@qq.com")
四.序列化
我这里是用的项目是前后端分离的(drf),如果是用的Django,则可以用表单验证(Form,ModelForm等)。
class EmailSerializer(serializers.Serializer): ''' 注册和邮箱验证码序列化 ''' email = serializers.CharField(max_length=30, min_length=5) def validate_email(self, email): ''' 验证邮箱 ''' # 验证邮箱是否合法 if not re.match(REGEX_EMAIL, email): raise serializers.ValidationError('邮箱非法') # 邮箱是否注册 if User.objects.filter(email=email).count(): raise serializers.ValidationError('用户已经存在') on_minute_ago = datetime.now() - timedelta(hours=0, minutes=1, seconds=0) if EmailVeriyRecord.objects.filter(send_time__gt=on_minute_ago, email=email, send_type='register'): raise serializers.ValidationError('距离上一次发送未超过60秒') return email
五.发送邮箱接口
class EmailCodeViewset(mixins.CreateModelMixin, viewsets.GenericViewSet): """ 邮箱验证码接口 create: 验证码发送至邮箱 """ serializer_class = EmailSerializer def create(self, request, *args, **kwargs): serializer = self.get_serializer(data=request.data) serializer.is_valid(raise_exception=True) email = serializer.validated_data['email'] code, email_status = send_register_email(email) if not email_status: return Response({'email': "验证发送失败"}, status=status.HTTP_400_BAD_REQUEST) else: email_record = EmailVeriyRecord() email_record.code = code email_record.email = email email_record.send_type = "register" email_record.save() return Response({'email': email}, status=status.HTTP_201_CREATED) self.perform_create(serializer) headers = self.get_success_headers(serializer.data) return Response(serializer.data, status=status.HTTP_201_CREATED, headers=headers)
六.心得体会
看似不难的东西,结果因为端口查了一下午的资料,嘿呀,都是眼泪花花啊,希望能找到一起交流学习的小伙伴,拒绝利益交友,只是希望能一同讨论共同进步,如果你感兴趣,请加QQ:1508414512,本人很友好热情,积极向上,做事认真负责,呃呃,词穷,反正不止这点优点。