import smtplib
import ssl
from email.mime.text import MIMEText
from email.mime.multipart import MIMEMultipart
from email.mime.application import MIMEApplication
import config


class mail:
    mail_cfg2 = config.MailConfig(**{
        'server': 'mail.psmanaged.com',
        'port': '465',
        'secure': 'ssl',
        'username': 'gc@scharf-automobile.de',
        'password': '+Js10TnD*km4E6',
        'email': 'gc@scharf-automobile.de'
    })

    def __init__(self):
        self.cfg = config.config()
        self.mail_cfg = self.cfg.smtp
        self.reply_to = self.cfg.kunde.replace(' ', '-').lower() + '@global-cube.de'
        self.context = ssl.create_default_context()

    def __enter__(self):
        try:
            self.mailserver = smtplib.SMTP_SSL(self.mail_cfg.server, self.mail_cfg.port, context=self.context)
            self.mailserver.login(self.mail_cfg.username, self.mail_cfg.password)
        except smtplib.SMTPException as e:
            print(e)
        return self

    def __exit__(self, exc_type, exc_val, exc_tb):
        self.mailserver.quit()

    def send(self, mailto, subject, html, attachment=None):
        msg = self.message(mailto, subject, html, attachment)

        try:
            result = self.mailserver.sendmail(self.reply_to, mailto, msg.as_string())
            print(result)
        except smtplib.SMTPException as e:
            print(e)

    def message(self, mailto, subject, html, attachment):
        msg = MIMEMultipart('alternative')
        msg['Reply-To'] = self.reply_to
        msg['From'] = f'Global Cube <{self.mail_cfg.email}>'
        msg['To'] = mailto
        msg['Subject'] = subject

        # msg.attach(MIMEText(text, 'plain'))
        msg.attach(MIMEText(html, 'html'))

        for name, filename in attachment or []:
            with open(filename, "rb") as f:
                part = MIMEApplication(f.read(), Name=name)
                part['Content-Disposition'] = f'attachment; filename="{name}"'
                msg.attach(part)
        return msg


if __name__ == '__main__':
    with mail() as m:
        m.send('robert.bedner@gmail.com', 'Test 123', ['C:\\GAPS\\Portal\\daten\\1_1_Taegliche_Erfolgskontrolle_1.pdf'])
