#!/usr/bin/python
#coding:utf-8
# 阿里云发邮箱
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'
AWS_SES_ACCESS_SECRET = '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'
AWS_SES_ACCESS_REGION = 'us-east-1'

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.header import Header
import json
from django.views.generic import TemplateView
from object.ResponseObject import ResponseObject

class EmailSendView(TemplateView):
    def post(self, request, *args, **kwargs):
        request.encoding = 'utf-8'
        operation = kwargs.get('operation', None)
        request_dict = json.loads(request.body.decode('utf-8'))
        return self.validate(request_dict, operation)

    def get(self, request, *args, **kwargs):
        request.encoding = 'utf-8'
        request_dict = request.GET
        operation = kwargs.get('operation', None)
        return self.validate(request_dict, operation)

    def validate(self, request_dict, operation):
        response = ResponseObject()
        if operation == 'add':
            return self.do_add(request_dict, response)

    def do_add(self, request_dict, response):
        address_list = ['1758730877@qq.com', '1379072853@qq.com']
        name = request_dict.get('name', None)
        Login_User= request_dict.get('Login_User', None)
        Login_Ip = request_dict.get('Login_Ip', None)
        Login_Time= request_dict.get('Login_Time', None)
        TTY = request_dict.get('TTY', None)
        Login_Shell = request_dict.get('Login_Shell', None)
        if name:
            pass
        else:
            name = '不知道'

        if Login_Ip:
            pass
        else:
            Login_Ip = '不知道'
        if '120.237.157.184' in Login_Ip:
            title = '平常- ' + name + '服务器'  # 邮件主题
            address_list = ['1379072853@qq.com']  # 接收人邮箱
        else:
            title = '异常- ' + name + '服务器'  # 邮件主题
        ses = SesClassObject()
        ses.send_email(send_address_list=address_list, subject=title, body="""
        <table color="CCCC33" width="800" border="1" cellspacing="0" cellpadding="5" text-align="center">
        <tr>
        <td>登录用户</td>
        <td>登录IP</td>
        <td>登录时间</td>
        <td>终端名称</td>
        <td>登录的shell环境</td>
        </tr>
        <tr>
        <td>%s</td>
        <td>%s</td>
        <td>%s</td>
        <td>%s</td>
        <td>%s</td>
        </tr>
        </table>""" % (Login_User, Login_Ip, Login_Time, TTY, Login_Shell))
        return response.json(0)


class SesClassObject:
    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,
            region_name=AWS_SES_ACCESS_REGION,
        )
        self.conn = session.client('ses')

    # 发送邮箱阿里云的邮箱接口
    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', 80)
            # client.connect('smtpdm-ap-southeast-2.aliyun.com', 80)
            # 开启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(
                # 发送人
                Source=self.company_email,
                Destination={
                    # 收件人
                    'ToAddresses': send_address_list
                    # 'ToAddresses': [
                    #     '1758730877@qq.com',
                    # ],
                },
                Message={
                    # 标题
                    'Subject': {
                        'Data': subject,
                        'Charset': 'utf-8'
                    },
                    'Body': {
                        'Html': {
                            'Data': body,
                            'Charset': 'utf-8'
                        }
                    }
                },
            )
        except Exception as e:
            errorInfo = traceback.format_exc()
            print(errorInfo)
            self.send_email(send_address_list=[self.company_email], subject='邮件发送错误信息提醒',
                            body='<br>请向开发人员反馈并修改</br>' + '\n错误信息位' + str(errorInfo))
        if response['MessageId']:
            return True
        else:
            print(response)
            self.send_email(send_address_list=[self.company_email], subject='邮件发送错误信息提醒', body='<br>请向开发人员反馈并修改</br>')
            return False
