import email.utils
import smtplib
from email.mime.multipart import MIMEMultipart
from email.mime.text import MIMEText

import boto3

from Ansjer.config import AWS_ACCESS_KEY_ID, AWS_SECRET_ACCESS_KEY, LOGGER


class S3Email:

    def faEmail(self, sys_msg_text, username):
        SENDER = 'rdpublic@ansjer.com'  # 邮箱名
        SENDERNAME = 'rdpublic@ansjer.com'
        USERNAME_SMTP = 'AKIA2E67UIMD6MOSFKXW'  # 带有邮件权限的 IAM 帐号
        PASSWORD_SMTP = 'BHuQ6EQTtFK4qh46o9omO9ZzO3NXzjk/JCWLXnVFmqzM'  # 带有邮件权限的 IAM 密码
        PORT = '587'
        HOST = 'email-smtp.us-east-1.amazonaws.com'
        SUBJECT = sys_msg_text
        BODY_TEXT = (sys_msg_text
                     )
        BODY_HTML = """<html>
        <head></head>
        <body>
          <h1>{}<h1>
        </body>
        </html>
                    """.format(sys_msg_text)

        msg = MIMEMultipart('alternative')
        msg['Subject'] = SUBJECT
        msg['From'] = email.utils.formataddr((SENDERNAME, SENDER))
        msg['To'] = username
        part1 = MIMEText(BODY_TEXT, 'plain')
        part2 = MIMEText(BODY_HTML, 'html')
        msg.attach(part1)
        msg.attach(part2)

        try:
            server = smtplib.SMTP(HOST, PORT)
            server.ehlo()
            server.starttls()
            server.ehlo()
            server.login(USERNAME_SMTP, PASSWORD_SMTP)
            server.sendmail(SENDER, username, msg.as_string())
            server.close()
        except Exception as e:
            print("Error: ", e)
        else:
            print("Email sent!")

    @staticmethod
    def send_email(subject, data, username):
        """
        发送亚马逊SES电子邮件
        @param subject: 标题
        @param data: 内容
        @param username: 发送到邮箱
        @return: 成功 | 失败
        """
        client = boto3.client('ses', region_name='us-east-1',
                              aws_access_key_id=AWS_ACCESS_KEY_ID[1],
                              aws_secret_access_key=AWS_SECRET_ACCESS_KEY[1])
        # 构建邮件请求
        response = client.send_email(
            Source='rdpublic@ansjer.com',  # 发件人地址
            Destination={
                'ToAddresses': [
                    username  # 收件人地址
                ]
            },
            Message={
                'Subject': {
                    'Data': subject  # 邮件主题
                },
                'Body': {
                    'Html': {
                        'Data': data  # 邮件正文的HTML内容
                    }
                }
            }
        )
        LOGGER.info(f'to {username},result:{response}')
        return response['ResponseMetadata']['HTTPStatusCode'] == 200
