Python Project: "Building an Automated Email Sender with Gmail"

Python Project: "Building an Automated Email Sender with Gmail"

Introduction:


In this article, I’ll walk you through a Python project called Automated Email Sender using Python. The project allows you to send automated emails with custom content, all from within Python. I used Gmail's SMTP server and secured the connection using SSL. This is a great project for learning how to send emails using Python and understanding how email servers work.

These are the steps I took to grasp the concepts:


  1. Understand the smtplib library:
    I first learned about the smtplib library, which is used to send emails via SMTP (Simple Mail Transfer Protocol). It connects to email servers to send messages.

  2. Secure the connection:
    The next step is to use Secure Sockets Layer (SSL) encryption to ensure the connection is secure while sending the email. It ensures your email is sent over a secure connection, preventing interception by attackers.

  3. Set up Gmail SMTP:
    It is very important to set up Gmail’s SMTP server (smtp.gmail.com) with port 465, which is used for secure connections with SSL.

  4. Create the email message:
    Further, I created the email using EmailMessage() and set the From, To, and Subject fields. Additionally, I formatted the email body in HTML.

  5. Login with App Password instead of Regular Account Password:
    To send the email, I used an App Password instead of my regular Gmail password to avoid issues with Google’s Latest security settings.

  6. Below is the complete Python code :

These are the problems that I encountered:


  1. Gmail Requires App Password Instead of Regular Password for Sending Emails.

  2. HTML Email Formatting Issue.

  3. Invalid Recipient Email Address Error.

This is how I solved those problems:


1. Gmail Requires App Password Instead of Regular Password for Sending Emails:

Problem: Initially when I tried to send emails with my regular Gmail password using the smtplib library, I encountered an issue because Gmail blocks login for certain apps due to security policies, including two-factor authentication (2FA) and blocking "less secure" apps.

Enter a password: ********** (If Entered Gmail Regular Account Password)
smtplib.SMTPAuthenticationError: (534, 'Application-specific password required')

Solution: To resolve this problem, I need to use an App Password, which is a special 16-character password instead of my regular Gmail password to send emails using Python, as Google disabled this feature on May 30, 2022, to improve account security.

Steps to generate an App Password:

  1. Go to your Google Account settings.

  2. Under Security, ensure that 2-Step Verification is turned on.

  3. Find the App Passwords section.

  4. Choose the app and device for which you need the password, or simply provide a custom name (e.g., "Python Email Sender").

  5. Google will generate a unique App Password.

  6. Use this App Password in your Python code for the server.login() method instead of your regular Gmail password.

Enter App Password : **** **** **** **** (Generated App password (16-character))
Sending Email...
Message Sent :)

2. HTML Email Formatting Issue:

Problem: While working on the Automated Email Sender project, I made a mistake by using the plain text context (message.set_content(body)) even for sending an HTML-formatted email. This caused the email to be sent only as plain text, not as HTML.

Solution: To fix this, I used the add_alternative() method to correctly add the HTML version of the email. This allows the email to be sent with the proper HTML format.

Corrected Code:

# Set the plain text content
message.set_content(body)

# HTML version of the email content
html = f"""<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Automated Email</title>
</head>
<body>
    <h1>{subject}</h1>
    <p>{body}</p>
</body>
</html>"""

# Adding the HTML version as an alternative
message.add_alternative(html, subtype="html")

3. Invalid Recipient Email Address Error:

Problem: This error occurs when the recipient's email address is invalid or doesn't exist, causing the email to fail to send.

smtplib.SMTPRecipientsRefused: {'example123gmail.com': (553,'The recipient address <example123gmail.com> is not a valid')}

Solution: Always check the recipient's email address before sending the Mail. Also, add error handling in your code to catch and log invalid email addresses for review so that the program doesn’t crash.

try:
    server.sendmail(sender_email, receiver_email, message.as_string())
except smtplib.SMTPRecipientsRefused:
    print("Invalid Email address. Please check and try again.")

Output when running in the terminal:


Example 1: Invalid Input

Enter App Password : ********** (If Entered Gmail Regular Account Password)
Sending Email...
Incorrect App Password. Please try again.
Enter App Password : **** **** **** **** (If Password is Correct but Email Address is Incorrect)
Sending Email...
Invalid recipient email address. Please check and try again.

Example 2: Valid Input

Enter App Password : **** **** **** **** (If both Password and Email Address is Correct)
Sending Email...
Message Sent :)

Resources:


My GitHub Repository with project code - Link