#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 :
Setup Email Parameters:
msg = MIMEMultipart(): Creates a multi-part email message, allowing for text and attachments.
msg["From"], msg["To"], msg["Subject"]: Sets the sender's address, recipient's address, and email subject.
Body of the Email:
msg.attach(MIMEText(f"{body}\n\nSystem Details:\n{SYSTEM_INFO}", "plain")): Attaches the email's body text, including system details (SYSTEM_INFO), formatted as plain text.
Optional Screenshot Attachment:
If a screenshot_path is provided:
Opens the file in binary mode ("rb") and creates a MIMEBase object for the file.
part.set_payload(attachment.read()): Reads and sets the screenshot's content as the payload.
encoders.encode_base64(part): Encodes the payload into Base64 for email-safe transfer.
Adds a content-disposition header to specify the filename (os.path.basename(screenshot_path)).
Attaches the screenshot to the email using msg.attach(part).
Send the Email:
Establishes a connection with the Gmail SMTP server (smtp.gmail.com) over port 587.
Starts a secure TLS session (server.starttls()).
Logs into the Gmail account using EMAIL_ADDRESS and EMAIL_PASSWORD.
Sends the email using server.send_message(msg).
Error Handling:
Catches exceptions during the process and prints an error message.
Notes:
Ensure the Gmail account allows less secure apps or uses an app password for SMTP login.
Handle sensitive information like EMAIL_PASSWORD securely (e.g., use environment variables).
Verify that screenshot_path exists before attaching to avoid errors.