import smtplib
from email.mime.text import MIMEText
from email.mime.multipart import MIMEMultipart
import email.utils
import logging
from datetime import datetime, timedelta, date
import time

mail_time = time.time()
mail_time_formatted = datetime.fromtimestamp(mail_time).strftime('%Y-%m-%d %H:%M:%S')

def sendExceptionMail(exception_msg, script_name, server_ip, e_time = str(mail_time_formatted)):
    # Replace these variables with your own values

    sender_email = "postmancollection7@gmail.com"
    receiver_emails = ["kriyans.p@upsquare.in", "vivek.f@upsquare.in"]
    password = "ixaqylsiglqpivgf"
    exception_title = "VPN Script"
    exception_subject = "Python Script Exception Occurred"
    
    # Create a MIME object
    message = MIMEMultipart()
    message["From"] = email.utils.formataddr((exception_title, sender_email))
    message["To"] = ", ".join(receiver_emails)  # Join the list of recipients with commas
    message["Subject"] = f"{exception_subject}"  

    # Add the body of the email
    body = f"""
        <html>
            <body>
                <p style="font-size: 20px"><strong>Script Running Stopped in <u>{script_name}</u></strong></p>
                <p style="font-size: 20px"><strong>Server IP: </strong>{server_ip}</p>
                <p style="font-size: 20px"><strong>Exception time: </strong>{e_time}</p>
                <p style="font-size: 20px"><strong> Exception message: </strong></p>
            </body>
        </html>
        """ 
    message.attach(MIMEText(body, "html"))

    body_exception = exception_msg

    message.attach(MIMEText(body_exception, "plain"))
    try:
    # Establish a connection to the Gmail SMTP server
        with smtplib.SMTP_SSL("smtp.gmail.com", 465) as server:
            server.login(sender_email, password)

            # Send the email
            server.sendmail(sender_email, receiver_emails, message.as_string())

        print("Exception report email sent successfully!")
        logging.info("-----------------------------------------------EXCEPTION_MAIL_SENT------------------------------------------")

    except Exception as e:
        print(f"Failed to send exception report email: {e}")
        print("Exception report email sent successfully!")
        logging.info("-----------------------------------------------MAIL_EXCEPTION_LOG-------------------------------------------")
        logging.error("Send Mail error", exc_info=True)
        logging.info("-------------------------------------------------------------------------------------------------")