فهرست منبع

Merge remote-tracking branch 'remotes/localServer/pzb' into test

chenjunkai 6 سال پیش
والد
کامیت
5251c137ec
3فایلهای تغییر یافته به همراه134 افزوده شده و 7 حذف شده
  1. 6 0
      Ansjer/config.py
  2. 44 3
      Controller/UserController.py
  3. 84 4
      Object/AWS/SesClassObject.py

+ 6 - 0
Ansjer/config.py

@@ -17,6 +17,12 @@ import datetime, os
 SERVER_TYPE = os.environ.get('DJANGO_SETTINGS_MODULE')
 print(SERVER_TYPE)
 
+# 阿里云发邮箱
+ALY_SES_ACCESS_NAME = 'message@dvema.com'
+ALY_SES_ACCESS_PAW = 'SMtp123456'
+ALY_SES_ACCESS_REPLYTO = '***'
+
+
 # 发送邮件邮箱
 SES_COMPANY_EMAIL = 'user_server@nsst.com'
 AWS_SES_ACCESS_ID = 'AKIAJKPU23EU5QWHFPKQ'

+ 44 - 3
Controller/UserController.py

@@ -540,7 +540,10 @@ class v2authCodeView(TemplateView):
         phone = request_dict.get('phone', None)
         if email is not None:
             email = email.strip()
-            return self.emailCode(email, response)
+            # 阿里云的发送邮箱的调用方法
+            return self.aliyun_emailCode(email, response)
+
+            # return self.emailCode(email, response)
         elif phone is not None:
             phone = phone.strip()
             return self.phoneCode(phone, response)
@@ -548,6 +551,7 @@ class v2authCodeView(TemplateView):
             return response.json(444)
 
     def emailCode(self, email, response):
+
         dataValid = DataValid()
         # 邮箱匹配
         if dataValid.email_validate(email) is False:
@@ -582,7 +586,41 @@ class v2authCodeView(TemplateView):
             return response.json(10, 'error')
         return response.json(0)
         # return response.json(0, {'identifyingCode': identifyingCode})
-
+    # 阿里云获取邮箱验证码
+    def aliyun_emailCode(self, email, response):
+        print ('阿里云开始')
+        dataValid = DataValid()
+        # 邮箱匹配
+        if dataValid.email_validate(email) is False:
+            return response.json(107)
+        reds = RedisObject()
+        identifyingCode = reds.get_data(key=email + '_identifyingCode')
+        # 是否以获取邮箱验证码
+        if identifyingCode:
+            return response.json(89)
+        user_qs = Device_User.objects.filter(username=email)
+        email_qs = Device_User.objects.filter(userEmail=email)
+        # 邮箱用户是否已存在
+        if user_qs.exists():
+            return response.json(103)
+        elif email_qs.exists():
+            return response.json(103)
+        # 生成随机6位数
+        identifyingCode = RandomStr(6, True)
+        # 设置随机数缓存生命周期
+        send_data = TemplateService.email_message(type='register_code', language=response.lang)
+        ses = SesClassObject()
+        # 发送邮件
+        send_res = ses.alyEmailCode(
+            send_address_list=[email],
+            subject=send_data['title'],
+            body=send_data['body'].replace("{username}", email).replace("{captcha}", str(identifyingCode))
+        )
+        if send_res is not True:
+            return response.json(44)
+        if reds.set_data(key=email + '_identifyingCode', val=identifyingCode, expire=600) is not True:
+            return response.json(10, 'error')
+        return response.json(0)
     def phoneCode(self, phone, response):
         dataValid = DataValid()
         if dataValid.mobile_validate(phone) is not True:
@@ -825,7 +863,10 @@ class v2forgetPwdCodeView(TemplateView):
         send_data = TemplateService.email_message(type='forgetCode', language=response.lang)
         send_body = send_data['body'].format(userEmail=email, email_valid_code=resetCode)
         ses = SesClassObject()
-        send_res = ses.send_email(send_address_list=[email], subject=send_data['title'], body=send_body)
+
+        # send_res = ses.send_email(send_address_list=[email], subject=send_data['title'], body=send_body)
+        # 阿里云发送邮箱
+        send_res = ses.alyEmailCode(send_address_list=[email], subject=send_data['title'], body=send_body)
         if send_res is not True:
             reds.del_data(key=email + '_forgetPwdResetCode')
             return response.json(44)

+ 84 - 4
Object/AWS/SesClassObject.py

@@ -1,13 +1,25 @@
-from Ansjer.config import AWS_SES_ACCESS_ID,AWS_SES_ACCESS_SECRET,AWS_SES_ACCESS_REGION,SES_COMPANY_EMAIL
+from Ansjer.config import ALY_SES_ACCESS_NAME,ALY_SES_ACCESS_PAW,ALY_SES_ACCESS_REPLYTO,AWS_SES_ACCESS_ID,AWS_SES_ACCESS_SECRET,AWS_SES_ACCESS_REGION,SES_COMPANY_EMAIL
+
 from boto3.session import Session
 import traceback
+import smtplib
+import email
+from email.mime.multipart import MIMEMultipart
+from email.mime.text import MIMEText
+from email.mime.image import MIMEImage
+from email.mime.base import MIMEBase
+from email.mime.application import MIMEApplication
+from email.header import Header
 
 class SesClassObject:
-    def __init__(self, *args, **kwargs):
+   def __init__(self, *args, **kwargs):
         self.access_id = AWS_SES_ACCESS_ID
         self.access_secret = AWS_SES_ACCESS_SECRET
         self.region_name = AWS_SES_ACCESS_REGION
         self.company_email = SES_COMPANY_EMAIL
+        self.aliyun_username = ALY_SES_ACCESS_NAME
+        self.aliyun_password = ALY_SES_ACCESS_PAW
+        self.aliyun_replyto = ALY_SES_ACCESS_REPLYTO
         session = Session(
             aws_access_key_id=AWS_SES_ACCESS_ID,
             aws_secret_access_key=AWS_SES_ACCESS_SECRET,
@@ -15,7 +27,74 @@ class SesClassObject:
         )
         self.conn = session.client('ses')
 
-    def send_email(self, send_address_list=[], subject='', body=''):
+   # 发送邮箱阿里云的邮箱接口
+   def alyEmailCode(self,send_address_list=[], subject='', body=''):
+       print ('我开始发送邮箱咯')
+       # 发件人地址,通过控制台创建的发件人地址
+       username = self.aliyun_username
+       # 发件人密码,通过控制台创建的发件人密码
+       password = self.aliyun_password
+       # 自定义的回复地址
+       replyto = self.aliyun_replyto
+       # 收件人地址或是地址列表,支持多个收件人,最多30个
+       # rcptto = '***,***'
+       # rcptto = '1758730877@qq.com'
+       rcptto = send_address_list
+       # 构建alternative结构
+       msg = MIMEMultipart('alternative')
+       msg['Subject'] = Header(subject).encode()
+       msg['From'] = '%s <%s>' % (Header('user_server').encode(), username)
+       # msg['To'] = rcptto
+       msg['Reply-to'] = replyto
+       msg['Message-id'] = email.utils.make_msgid()
+       msg['Date'] = email.utils.formatdate()
+       # 构建alternative的text/plain部分
+       # textplain = MIMEText('自定义TEXT纯文本部分', _subtype='plain', _charset='UTF-8')
+       # msg.attach(textplain)
+       texthtml = MIMEText(body, _subtype='html', _charset='UTF-8')
+
+       msg.attach(texthtml)
+
+       # 发送邮件
+       try:
+           client = smtplib.SMTP()
+           # python 2.7以上版本,若需要使用SSL,可以这样创建client
+           # client = smtplib.SMTP_SSL()
+           # SMTP普通端口为25或80
+           client.connect('smtpdm.aliyun.com', 25)
+           # 开启DEBUG模式
+           client.set_debuglevel(0)
+           client.login(username, password)
+           # 发件人和认证地址必须一致
+           # 备注:若想取到DATA命令返回值,可参考smtplib的sendmaili封装方法:
+           #      使用SMTP.mail/SMTP.rcpt/SMTP.data方法
+           client.sendmail(username, rcptto, msg.as_string())
+           client.quit()
+           print('邮件发送成功')
+           return True
+       except smtplib.SMTPConnectError as e:
+           print('邮件发送失败,连接失败:', e.smtp_code, e.smtp_error)
+           return False
+       except smtplib.SMTPAuthenticationError as e:
+           print('邮件发送失败,认证错误:', e.smtp_code, e.smtp_error)
+           return False
+       except smtplib.SMTPSenderRefused as e:
+           print('邮件发送失败,发件人被拒绝:', e.smtp_code, e.smtp_error)
+           return False
+       except smtplib.SMTPRecipientsRefused as e:
+           print('邮件发送失败,收件人被拒绝:', e.smtp_code, e.smtp_error)
+           return False
+       except smtplib.SMTPDataError as e:
+           print('邮件发送失败,数据接收拒绝:', e.smtp_code, e.smtp_error)
+           return False
+       except smtplib.SMTPException as e:
+           print('邮件发送失败, ', e.message)
+           return False
+       except Exception as e:
+           print('邮件发送异常, ', str(e))
+           return False
+
+   def send_email(self, send_address_list=[], subject='', body=''):
         try:
             response = self.conn.send_email(
                 # 发送人
@@ -50,4 +129,5 @@ class SesClassObject:
         else:
             print(response)
             self.send_email(send_address_list=[self.company_email],subject='邮件发送错误信息提醒',body='<br>请向开发人员反馈并修改</br>')
-            return False
+            return False
+