import ssl
import smtplib
from email import encoders
from email.mime.base import MIMEBase
from email.mime.text import MIMEText
from email.mime.multipart import MIMEMultipart


class SMTPUtility:
    def __init__(self):
        self.from_address = "dasharatha.vamshi@knowledgelens.com"
        self.to_address = ["saivamshi2309@gmail.com", "saivamshi.s16@iiits.in"]
        self.msg = MIMEMultipart()
        self.msg['From'] = self.from_address
        self.msg['To'] = " ,".join(self.to_address)
        self.filename = ""
        self.smtp_server = "smtp.gmail.com"
        self.username = "dasharatha.vamshi@knowledgelens.com"
        self.password = "Salla$230999"
        self.smtp_server_port = 587
        self.ssl = False

    def send_email(self, content, attach=False):
        try:
            self.msg['Subject'] = "KL Bot: " + content['subject']
            self.msg['body'] = content['body']
            self.msg.attach(MIMEText(self.msg['body'], 'plain'))

            # give filename in self.filename to attach a document.
            if attach:
                attachment = open(self.filename, "rb")
                p = MIMEBase('application', 'octet-stream')
                p.set_payload(attachment.read())
                encoders.encode_base64(p)
                p.add_header('Content-Disposition', "attachment; filename= %s" % self.filename)
                self.msg.attach(p)

            # starting the sever
            if self.ssl:
                context = ssl.create_default_context()
                with smtplib.SMTP_SSL(self.smtp_server, self.smtp_server_port, context=context) as server:
                    server.login(self.username, self.password)
                    server.sendmail(self.from_address, self.to_address, self.msg.as_string())
            else:
                s = smtplib.SMTP(self.smtp_server, self.smtp_server_port)
                s.starttls()
                s.login(self.username, self.password)
                s.sendmail(self.from_address, self.to_address, self.msg.as_string())
                s.quit()
            return True
        except:
            return False
