From e6371ccde941df5c83163504561029a7bf7b3647 Mon Sep 17 00:00:00 2001 From: smog-root Date: Sat, 2 Nov 2024 15:02:47 +0530 Subject: [PATCH] Enhanced send_email.py Script for Improved Security, Flexibility, and Error Handling --- pysnippets/Communication/send_email.py | 91 ++++++++++++++------------ 1 file changed, 49 insertions(+), 42 deletions(-) diff --git a/pysnippets/Communication/send_email.py b/pysnippets/Communication/send_email.py index 88f7ff9d..db218995 100644 --- a/pysnippets/Communication/send_email.py +++ b/pysnippets/Communication/send_email.py @@ -1,50 +1,44 @@ import smtplib +import os from email.mime.text import MIMEText from email.mime.multipart import MIMEMultipart +from typing import Optional def send_email( - sender_email, - sender_password, - recepient_email, - subject, - body, - smtp_server="smtp.gmail.com", - smtp_port=587, -): + sender_email: str, + sender_password: str, + recipient_email: str, + subject: str, + body: str, + content_type: str = "plain", + smtp_server: str = "smtp.gmail.com", + smtp_port: int = 587, +) -> bool: """ - Sends an email using the provided SMTP server. + Sends an email to the specified recipient. Args: - sender_email (str): The email address of the sender. + sender_email (str): The sender's email address. sender_password (str): The password for the sender's email account. - recepient_mail (str): The email address of the recepient. - subject (str): The subject of the email. - body (str): The body of the email. - smtp_server (str, optional): The SMTP server to use. Defaults to 'smtp.gmail.com'. + recipient_email (str): The recipient's email address. + subject (str): The subject line of the email. + body (str): The content of the email. + content_type (str, optional): The format of the email body, either 'plain' or 'html'. Defaults to 'plain'. + smtp_server (str, optional): The SMTP server to connect to. Defaults to 'smtp.gmail.com'. smtp_port (int, optional): The port to use for the SMTP server. Defaults to 587. - Raises: - smtplib.SMTPAuthenticationError: If authentication fails. - smtplib.SMTPException: If there's an error sending the email. - - Example: - send_email( - "aashishnkumar@gmail.com", - "your_password", - "aashishnandakumar.official.in@gmail.com", - "Test Subject", - "This is a test email", - ) + Returns: + bool: True if the email is sent successfully, False otherwise. """ # create the email message message = MIMEMultipart() message["From"] = sender_email - message["To"] = recepient_email + message["To"] = recipient_email message["Subject"] = subject # attach the body of the email - message.attach(MIMEText(body, "plain")) + message.attach(MIMEText(body, content_type)) try: # create a secure SSL/TLS connection @@ -55,22 +49,35 @@ def send_email( # send the email server.send_message(message) print("Email sent successfully!") + return True except smtplib.SMTPAuthenticationError: - print( - "SMTP Authentication Error: The server didn't accept the username/password combination." - ) - raise + print("SMTP Authentication Error: Please check your credentials.") + except smtplib.SMTPConnectError: + print("SMTP Connection Error: Unable to connect to the SMTP server.") + except smtplib.SMTPServerDisconnected: + print("SMTP Disconnection Error: The server unexpectedly disconnected.") except smtplib.SMTPException as e: - print(f"SMTP Error: An error occured while sending the email: {str(e)}") - raise + print(f"SMTP Error: An error occurred while sending the email: {str(e)}") + except Exception as e: + print(f"Network Error: A network-related error occurred: {str(e)}") + + return False if __name__ == "__main__": - # NOTE: Never hardcode sensitive information like this in practice - send_email( - "sender@gmail.com", - "password", - "receiver@gmail.com", - "Test Subject", - "This is a test Email", - ) + # Load credentials from environment variables for security + sender_email = os.getenv("SENDER_EMAIL") + sender_password = os.getenv("SENDER_PASSWORD") + + # Ensure credentials are provided + if not sender_email or not sender_password: + print("Error: Please set the SENDER_EMAIL and SENDER_PASSWORD environment variables.") + else: + send_email( + sender_email=sender_email, + sender_password=sender_password, + recipient_email="receiver@gmail.com", + subject="Test Subject", + body="

This is a test email

This email contains HTML formatting.

", + content_type="html" + ) \ No newline at end of file