Skip to content

Commit

Permalink
Enhanced send_email.py Script for Improved Security, Flexibility, and…
Browse files Browse the repository at this point in the history
… Error Handling
  • Loading branch information
smog-root committed Nov 2, 2024
1 parent 96a6a5a commit e6371cc
Showing 1 changed file with 49 additions and 42 deletions.
91 changes: 49 additions & 42 deletions pysnippets/Communication/send_email.py
Original file line number Diff line number Diff line change
@@ -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(
"[email protected]",
"your_password",
"[email protected]",
"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
Expand All @@ -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(
"[email protected]",
"password",
"[email protected]",
"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="[email protected]",
subject="Test Subject",
body="<h1>This is a test email</h1><p>This email contains HTML formatting.</p>",
content_type="html"
)

0 comments on commit e6371cc

Please sign in to comment.