# coding=utf-8
from __future__ import unicode_literals, print_function, absolute_import


import smtplib
from email.mime.text import MIMEText

from django.conf import settings

from rpc.tool.log_tool import logging_exception


class InternalEmailClient(object):

    def __init__(self, address, host, username, password):
        self.__address = address
        self.__host = host
        self.__username = username
        self.__password = password

    def send(self, to_addresses, subject, content):
        msg = MIMEText(content, 'html', 'utf-8')
        msg['from'] = self.__address
        msg['subject'] = subject

        conn = smtplib.SMTP_SSL()
        try:
            conn.connect(self.__host)
            conn.login(self.__username, self.__password)
            conn.sendmail(self.__address, to_addresses, msg.as_string())
            conn.quit()
        except:
            logging_exception()
        finally:
            conn.close()


def send_internal_email(to_addresses, subject, content, from_addresses=settings.INTERNAL_EMAIL):

    config = from_addresses
    client = InternalEmailClient(
        address=config['address'],
        host=config['host'],
        username=config['username'],
        password=config['password'],
    )
    client.send(to_addresses=to_addresses, subject=subject, content=content)


def send_user_email(to_addresses, subject, content, from_addresses=settings.NO_REPLY_EMAIL):
    send_internal_email(to_addresses, subject, content, from_addresses)
