#function to send an email

 

def send_email(subject, body, screenshot_path=None):

try:

     msg = MIMEMultipart()

        msg["From"] = EMAIL_ADDRESS

        msg["To"] = TO_EMAIL

        msg["Subject"] = subject

        msg.attach(MIMEText(f"{body}\n\nSystem Details:\n{SYSTEM_INFO}", "plain"))

     if screenshot_path:

            attachment = open(screenshot_path, "rb")

         part = MIMEBase("application", "octet-stream")

            part.set_payload(attachment.read())

            encoders.encode_base64(part)

            part.add_header("Content-Disposition", f"attachment; filename={os.path.basename(screenshot_path)}")

            msg.attach(part)

            attachment.close()

     with smtplib.SMTP("smtp.gmail.com", 587) as server:

            server.starttls()

            server.login(EMAIL_ADDRESS, EMAIL_PASSWORD)

            server.send_message(msg)

        print("Alert email sent.")

except Exception as e:

        print(f"Failed to send email: {e}")

 

Explanation:

This function, send_email, sends an email with an optional screenshot attachment. Here's a breakdown of how it works:

Components :

Notes: