# Automated Email Sender with Python

Sending emails automatically is a common task in both personal projects and professional applications. Whether you want to send reports, reminders, or alerts, learning how to send emails using Python is a valuable skill.

In this article, you'll learn how to build a simple yet powerful **Automated Email Sender** in Python using the built-in `smtplib` and `email` modules.

## What You'll Learn

* How to set up SMTP for Gmail (or another provider)
    
* How to structure and send emails (plain text and HTML)
    
* How to add attachments
    
* How to automate sending
    

Let’s get started.

## Prerequisites

You only need Python. We’ll use built-in modules:

* `smtplib` for sending mail via SMTP
    
* `email.mime` for crafting rich email content
    

**Note**: If you're using **Gmail**, you’ll need to [enable App Passwords](https://support.google.com/accounts/answer/185833?hl=en) if two-factor authentication is turned on. Otherwise, you can allow **"Less secure app access"** (not recommended for production use).

## Step-by-Step Script with Explanations

We'll now walk through the process, with clear steps and explanations.

### Step 1: Import Required Modules

```python
import smtplib                                     # For sending emails
from email.mime.text import MIMEText               # For plain text or HTML emails
from email.mime.multipart import MIMEMultipart     # For combining message parts
from email.mime.application import MIMEApplication # For attachments
import os                                          # For file handling
```

* We need these modules to compose and send emails, attach files, and handle MIME types.
    

### Step 2: Define Email Credentials and Settings

```python
sender_email = "youremail@gmail.com"       # Replace with your email
receiver_email = "receiver@example.com"    # Recipient's email
password = "your_app_password"             # Use App Password if using Gmail

subject = "Automated Email from Python"
body = "Hello, this is a test email sent automatically using Python!"
```

* Provide sender and recipient email addresses
    
* Set your subject line and body message
    

> Use environment variables for `password` in real applications to avoid hardcoding sensitive data.

### Step 3: Create the Email Message

```python
# Create a multipart message container
message = MIMEMultipart()
message["From"] = sender_email
message["To"] = receiver_email
message["Subject"] = subject

# Attach the email body (plain text)
message.attach(MIMEText(body, "plain"))
```

* `MIMEMultipart` allows combining text, HTML, and attachments
    
* We add a plain-text body using `MIMEText`
    

### Step 4: (Optional) Add an Attachment

```python
file_path = "example.pdf"  # Replace with your actual file path

if os.path.exists(file_path):
    with open(file_path, "rb") as f:
        part = MIMEApplication(f.read(), Name=os.path.basename(file_path))
    part['Content-Disposition'] = f'attachment; filename="{os.path.basename(file_path)}"'
    message.attach(part)
```

* We check if the file exists, open it in binary mode, and attach it
    
* The MIME application format is used for arbitrary files like PDFs, images, etc.
    

### Step 5: Connect to the SMTP Server and Send

```python
try:
    with smtplib.SMTP("smtp.gmail.com", 587) as server:
        server.starttls()  # Secure the connection
        server.login(sender_email, password)
        server.sendmail(sender_email, receiver_email, message.as_string())
        print("✅ Email sent successfully!")

except Exception as e:
    print("❌ Failed to send email:", e)
```

* We connect to Gmail's SMTP server
    
* `starttls()` initiates a secure connection
    
* We log in and send the message using `sendmail()`
    
* Errors are caught and displayed if sending fails
    

## Gmail SMTP Configuration Recap

* SMTP Server: `smtp.gmail.com`
    
* Port: `587`
    
* Requires TLS: Yes
    
* Requires Authentication: Yes
    

> **Important**: If using Gmail with 2FA, create an **App Password** at [https://myaccount.google.com/apppasswords](https://myaccount.google.com/apppasswords).

## Full Working Script

Here's everything combined into a single script:

```python
import smtplib
from email.mime.text import MIMEText
from email.mime.multipart import MIMEMultipart
from email.mime.application import MIMEApplication
import os

# Email credentials and message setup
sender_email = "youremail@gmail.com"
receiver_email = "receiver@example.com"
password = "your_app_password"  # Use an app-specific password

subject = "Automated Email from Python"
body = "Hello, this is a test email sent automatically using Python!"

# Create multipart email
message = MIMEMultipart()
message["From"] = sender_email
message["To"] = receiver_email
message["Subject"] = subject
message.attach(MIMEText(body, "plain"))

# Optional: Add an attachment
file_path = "example.pdf"
if os.path.exists(file_path):
    with open(file_path, "rb") as f:
        part = MIMEApplication(f.read(), Name=os.path.basename(file_path))
    part['Content-Disposition'] = f'attachment; filename="{os.path.basename(file_path)}"'
    message.attach(part)

# Send email
try:
    with smtplib.SMTP("smtp.gmail.com", 587) as server:
        server.starttls()
        server.login(sender_email, password)
        server.sendmail(sender_email, receiver_email, message.as_string())
        print("✅ Email sent successfully!")
except Exception as e:
    print("❌ Failed to send email:", e)
```

## Final Thoughts

With this script, you've learned how to:

* Send plain-text emails from Python
    
* Add file attachments
    
* Connect to SMTP servers like Gmail
    
* Automate one of the most common workflows in programming
    

This lays the foundation for more complex tools like:

* Sending reports at scheduled times
    
* Building notification systems
    
* Emailing logs or backups automatically
