# βιβλιοθήκη για αποστολή email μέσω σχολικού δικτύου
import smtplib, ssl, time
from gr_sch_helper import sch 
from email.message import EmailMessage
from email.utils import formatdate


port = lambda: sch.get_config('Mail', 'Port')
smtp_server = lambda: sch.get_config('Mail', 'Url')
username = lambda: sch.get_config('Mail', 'Username')                
password = lambda: sch.get_config('Mail', 'Password')
from_mail = lambda: sch.get_config('Mail', 'From')

context = ssl.create_default_context()

# αποστολή απλών μυνημάτων - χωρίς συνημμένα
# το EpalAuto = True αντιστοιχεί σε φίλτρο που
# μεταφέρει τα μυνήματα εκτός inbox
def sendMail(messages):
    #if port = 465
    with smtplib.SMTP(smtp_server(), port(), timeout=30) as server:
        server.ehlo()
        server.starttls(context=context)
        server.ehlo()       
        server.login(username(), password())
        for message in messages:
            msg = EmailMessage()
            msg.set_content(message['body'])
            msg["Date"] = formatdate(localtime=True)
            msg['Subject'] = message['subject']
            msg['From'] = from_mail()
            msg['To'] = message['to']
            msg['Bcc'] = message['bcc']
            msg['EpalAuto']="True"
            # attachment (only pdf / xlsx)
            if message.get("attach"):
                for filename, filetype in message["attach"]:
                    if filetype == "pdf":
                        maintype, subtype = "application", "pdf"
                    elif filetype == "xlsx":
                        maintype, subtype = (
                            "application",
                            "vnd.openxmlformats-officedocument.spreadsheetml.sheet",
                        )
                    else:
                        raise ValueError("Unsupported attachment type")

                    with open(filename, "rb") as f:
                        msg.add_attachment(
                            f.read(),
                            maintype=maintype,
                            subtype=subtype,
                            filename=filename,
                        )
            print("sending to " + message['to'])
            server.send_message(msg)
            print("sent")
            time.sleep(2)

        
# απλή κλάση για να γίνεται αυτόματα το login/logout στον smtp server
# χωρίς να ασχολούμαστε κάθε φορά με τις ρυθμίσεις 
class MyMailer:
    def __enter__(self):
        self.smtp = smtplib.SMTP_SSL(smtp_server(), port(), context=context)
        self.smtp.login(username(),password())
        return self.smtp

    def __exit__(self, exc_type, exc_val, exc_tb):
        self.smtp.quit()
        return False

