Python & Data Science

Sending Automated Emails And Reports From A Python

The Problem: You’ve Built a Great Report — But No One Sees It

You just spent three hours building a beautiful pandas report. You cleaned the data, created a summary table, made a chart, and exported everything to a CSV file. Then you popped open Gmail, attached the CSV, wrote a quick note, and hit send.

Next week you’ll do the same thing. And the week after that. And the week after that.

It’s boring. You forget sometimes. You’ve definitely sent the wrong file once (or twice). And you’re wasting 30 minutes every Monday on a task a computer could do for you.

What if your Python script could do the emailing for you? Imagine finishing your analysis, running one script, and then — the email is just… sent. Automatically. On a schedule.

That’s exactly what you’re going to build in this article. Step by step, with intuition first, then code, then a clear look at what your results mean. By the end, you’ll have a reusable email-pipeline that turns any pandas report into an automatic email delivery.

Let’s get started.

What’s Actually Going On Here? The Email Pipeline in Plain English

Before you write a single line of code, let’s understand the pieces involved. Think of it like mailing a physical letter.

You write a letter (the message). You put it in an envelope that can also hold photos or documents. You hand the envelope to the post office, which uses their delivery trucks to get it where it needs to go. The whole trip happens inside a locked box so nobody reads your mail.

Now map that to email:

  • The message is your email body — plain text or fancy HTML.
  • The envelope is called MIME (Multipurpose Internet Mail Extensions). It’s the format that lets you send text, images, and file attachments all together.
  • The post office delivery truck is SMTP (Simple Mail Transfer Protocol). It’s the set of rules your computer uses to hand your email to a mail server (like Gmail’s).
  • The locked box is TLS/SSL encryption. It makes a secure tunnel so your password and report stay private.

You don’t need to understand the technical details of these protocols. You just need to know which Python libraries do the work. We’ll use smtplib for the SMTP delivery truck, email.mime for the MIME envelope, and Python’s built-in ssl module for the locked box.

Here’s the catch: Your email provider (Gmail, Outlook, etc.) requires you to prove who you are before you can send mail through their server. That’s where authentication comes in — which is the first step we’ll tackle.

Step 1: Setting Up Your Email Credentials (Safely)

The most common beginner mistake is hardcoding your email password directly in your script. Don’t do this. If you share your code on GitHub, your password goes with it. If your coworker runs your script, they can see your password in plain text.

Instead, use environment variables. Think of them like sticky notes your computer keeps hidden from your code files. Your script reads the sticky note at runtime, but the password itself never appears in your source code.

Here’s how to set it up.

First, create a .env file in the same folder as your Python script. This file will hold your credentials. Never upload this file to GitHub (add .env to your .gitignore).

EMAIL_ADDRESS=youremail@gmail.com
EMAIL_PASSWORD=your_gmail_app_password

Second, install python-dotenv so Python can read that .env file.

pip install python-dotenv

Third, load the credentials in your script.

import os
from dotenv import load_dotenv

# Load the .env file
load_dotenv()

# Read credentials into variables
email_address = os.getenv('EMAIL_ADDRESS')
email_password = os.getenv('EMAIL_PASSWORD')

# Check they loaded (but don't print the password)
if email_address and email_password:
    print(f"✅ Credentials loaded for {email_address}")
else:
    print("❌ Could not load credentials. Check your .env file.")

When you run this, you’ll see:

✅ Credentials loaded for youremail@gmail.com

Wait — why use a Gmail App Password? If you have two-factor authentication (2FA) enabled on your Gmail (which you should), your regular password won’t work for SMTP. Google requires a special 16-character App Password.

To get one:

  1. Go to your Google Account.
  2. Click Security.
  3. Under Signing in to Google, turn on 2-Step Verification if it’s not already on.
  4. Search for App passwords in the Google Account search bar.
  5. Select Mail as the app and Other as the device (name it “Python Script”).
  6. Copy the 16-character password — use it as EMAIL_PASSWORD in your .env file.

Your credentials are now safe and your script is ready to move on.

Step 2: Building the Email Message (Text + Attachments)

Now let’s build the letter inside the envelope. We’ll create a MIMEMultipart message — think of it as a folder that can hold different parts: the email body (text) and the attached file.

We’ll use:

  • MIMEText to create the email body (plain text or HTML).
  • MIMEApplication to attach a file (like a CSV exported from pandas).
  • MIMEMultipart to combine them into one message.

Let’s see this in action with a real pandas DataFrame.

import pandas as pd
from email.mime.multipart import MIMEMultipart
from email.mime.text import MIMEText
from email.mime.application import MIMEApplication
import os
from dotenv import load_dotenv

# Load credentials (we'll need them later)
load_dotenv()
email_address = os.getenv('EMAIL_ADDRESS')

# ---- Build a sample pandas DataFrame (simulating your report) ----
df = pd.DataFrame({
    'Product': ['A', 'B', 'C'],
    'Sales': [100, 200, 150],
    'Revenue': [1000, 2500, 1800]
})

# ---- Create the MIMEMultipart message (the envelope) ----
msg = MIMEMultipart()
msg['From'] = email_address
msg['To'] = 'recipient@example.com'
msg['Subject'] = 'Weekly Sales Report'

# ---- Build the email body (HTML version) ----
html_body = f"""
<html>
<body>
<h2>Weekly Sales Summary</h2>
<p>Here is your report generated on {pd.Timestamp.now().strftime('%Y-%m-%d %H:%M')}.</p>
<table border="1" cellpadding="5">
<tr><th>Product</th><th>Sales</th><th>Revenue</th></tr>
{''.join(f'<tr><td>{row["Product"]}</td><td>{row["Sales"]}</td><td>{row["Revenue"]}</td></tr>' for _, row in df.iterrows())}
</table>
<p>This report has <b>{len(df)} rows</b> and <b>{len(df.columns)} columns</b>.</p>
</body>
</html>
"""

# Attach the HTML body as a MIMEText object
msg.attach(MIMEText(html_body, 'html'))

# ---- Export the DataFrame to CSV and attach it ----
csv_data = df.to_csv(index=False)
attachment = MIMEApplication(csv_data.encode('utf-8'), _subtype='csv')
attachment.add_header('Content-Disposition', 'attachment', filename='sales_report.csv')
msg.attach(attachment)

# ---- Print a summary of what we built ----
print(f"✅ Message created successfully.")
print(f"   From: {msg['From']}")
print(f"   To: {msg['To']}")
print(f"   Subject: {msg['Subject']}")
print(f"   Attachments: 1 CSV file (sales_report.csv)")
print(f"   HTML body contains a table of {len(df)} rows.")

When you run this, you’ll see:

✅ Message created successfully.
   From: youremail@gmail.com
   To: recipient@example.com
   Subject: Weekly Sales Report
   Attachments: 1 CSV file (sales_report.csv)
   HTML body contains a table of 3 rows.

Notice what happened: We built the entire email in memory — the HTML table is generated dynamically from the DataFrame, and the CSV is attached as a string without saving a file to disk. This keeps your pipeline clean and fast.

Step 3: Connecting to the SMTP Server and Sending

Now we hand the envelope to the post office. We’ll connect to Gmail’s SMTP server, log in using our credentials, send the message, and close the connection.

The key is using .starttls() — this creates the secure tunnel (the locked box) so your password and report aren’t sent in plain text over the internet.

import smtplib
import ssl
import os
from dotenv import load_dotenv
from email.mime.multipart import MIMEMultipart
from email.mime.text import MIMEText
from email.mime.application import MIMEApplication
import pandas as pd

# ---- Load credentials ----
load_dotenv()
email_address = os.getenv('EMAIL_ADDRESS')
email_password = os.getenv('EMAIL_PASSWORD')

# ---- Build the sample DataFrame and message (same as Step 2) ----
df = pd.DataFrame({
    'Product': ['A', 'B', 'C'],
    'Sales': [100, 200, 150],
    'Revenue': [1000, 2500, 1800]
})

msg = MIMEMultipart()
msg['From'] = email_address
msg['To'] = 'recipient@example.com'
msg['Subject'] = 'Weekly Sales Report'

html_body = f"""
<html>
<body>
<h2>Weekly Sales Summary</h2>
<p>Here is your report generated on {pd.Timestamp.now().strftime('%Y-%m-%d %H:%M')}.</p>
<table border="1" cellpadding="5">
<tr><th>Product</th><th>Sales</th><th>Revenue</th></tr>
{''.join(f'<tr><td>{row["Product"]}</td><td>{row["Sales"]}</td><td>{row["Revenue"]}</td></tr>' for _, row in df.iterrows())}
</table>
</body>
</html>
"""
msg.attach(MIMEText(html_body, 'html'))

csv_data = df.to_csv(index=False)
attachment = MIMEApplication(csv_data.encode('utf-8'), _subtype='csv')
attachment.add_header('Content-Disposition', 'attachment', filename='sales_report.csv')
msg.attach(attachment)

# ---- Connect to Gmail's SMTP server and send ----
try:
    # Create a secure SSL context
    context = ssl.create_default_context()

    # Connect to Gmail's SMTP server on port 587 (TLS)
    with smtplib.SMTP('smtp.gmail.com', 587) as server:
        server.starttls(context=context)  # Start the secure tunnel
        server.login(email_address, email_password)  # Log in
        server.send_message(msg)  # Send the email

    print("✅ Email sent successfully!")
    print(f"   To: {msg['To']}")
    print(f"   Subject: {msg['Subject']}")

except smtplib.SMTPAuthenticationError:
    print("❌ Authentication failed. Check your username/password.")
    print("   If using Gmail, make sure you're using an App Password, not your regular password.")
except smtplib.SMTPException as e:
    print(f"❌ SMTP error occurred: {e}")
except Exception as e:
    print(f"❌ An unexpected error occurred: {e}")

When this works, you’ll see:

✅ Email sent successfully!
   To: recipient@example.com
   Subject: Weekly Sales Report

What this means: Your email (with the HTML table and the CSV attachment) is now in Gmail’s outbox. It usually arrives in the recipient’s inbox within seconds.

But here’s the catch in real code: Network issues, wrong credentials, or temporary server problems can cause failures. That’s why we use the try-except block — it catches common errors and tells you exactly what went wrong.

Step 4: Putting It All Together — A Real Report Email

Let’s turn everything into a reusable function you can drop into any project.

import smtplib
import ssl
import os
import pandas as pd
from email.mime.multipart import MIMEMultipart
from email.mime.text import MIMEText
from email.mime.application import MIMEApplication
from dotenv import load_dotenv

def send_report(df, recipient_email, report_title="Data Report"):
    """
    Send a pandas DataFrame as an email report with:
    - An HTML summary table in the email body
    - The full DataFrame attached as a CSV file

    Parameters:
    df (pd.DataFrame): The data to send
    recipient_email (str): Recipient's email address
    report_title (str): Subject and report name
    """
    # Load credentials
    load_dotenv()
    email_address = os.getenv('EMAIL_ADDRESS')
    email_password = os.getenv('EMAIL_PASSWORD')

    if not email_address or not email_password:
        print("❌ Credentials not found. Check your .env file.")
        return

    # ---- Build the email message ----
    msg = MIMEMultipart()
    msg['From'] = email_address
    msg['To'] = recipient_email
    msg['Subject'] = report_title

    # HTML body with summary
    html_body = f"""
    <html>
    <body>
    <h2>{report_title}</h2>
    <p>Generated on: {pd.Timestamp.now().strftime('%Y-%m-%d %H:%M')}</p>
    <p>This report contains <b>{len(df)} rows</b> and <b>{len(df.columns)} columns</b>.</p>
    <h3>Preview (first 5 rows):</h3>
    {df.head(5).to_html(index=False)}
    </body>
    </html>
    """
    msg.attach(MIMEText(html_body, 'html'))

    # CSV attachment
    csv_data = df.to_csv(index=False)
    attachment = MIMEApplication(csv_data.encode('utf-8'), _subtype='csv')
    attachment.add_header('Content-Disposition', 'attachment', filename=f'{report_title.replace(" ", "_")}.csv')
    msg.attach(attachment)

    # ---- Send via SMTP ----
    try:
        context = ssl.create_default_context()
        with smtplib.SMTP('smtp.gmail.com', 587) as server:
            server.starttls(context=context)
            server.login(email_address, email_password)
            server.send_message(msg)
        print(f"✅ '{report_title}' sent to {recipient_email}")
    except Exception as e:
        print(f"❌ Failed to send report: {e}")

# ---- Example usage ----
if __name__ == "__main__":
    # Create a sample DataFrame
    df = pd.DataFrame({
        'Product': ['A', 'B', 'C', 'D', 'E', 'F'],
        'Sales': [100, 200, 150, 300, 250, 180],
        'Revenue': [1000, 2500, 1800, 3600, 3000, 2160]
    })

    # Send the report
    send_report(df, 'recipient@example.com', 'Weekly Sales Report')

When you run this, you’ll see:

✅ 'Weekly Sales Report' sent to recipient@example.com

Now here’s the interesting part: You can call send_report() at the end of any analysis script. Whether you’re analyzing sales data, sensor readings, or survey results, one function sends a polished report to your inbox — or to your boss’s inbox.

Step 5: Scheduling the Email to Run Automatically

The pipeline is built, but you still have to run the script manually. Let’s automate the trigger using Python’s schedule library.

First install it:

pip install schedule

Now we’ll set up the script to run every Monday at 9 AM.

import schedule
import time
import pandas as pd
from dotenv import load_dotenv

# Assume send_report is defined above (from Step 4)
# We'll recreate it here so the block is self-contained

def send_report(df, recipient_email, report_title="Data Report"):
    """Same function as Step 4 — see above for full code.
    For brevity, we'll define a minimal version here."""
    import smtplib
    import ssl
    import os
    from email.mime.multipart import MIMEMultipart
    from email.mime.text import MIMEText
    from email.mime.application import MIMEApplication

    load_dotenv()
    email_address = os.getenv('EMAIL_ADDRESS')
    email_password = os.getenv('EMAIL_PASSWORD')

    if not email_address or not email_password:
        print("❌ Credentials not found")
        return

    msg = MIMEMultipart()
    msg['From'] = email_address
    msg['To'] = recipient_email
    msg['Subject'] = report_title

    html_body = f"<html><body><h2>{report_title}</h2><p>Generated: {pd.Timestamp.now()}</p><p>{len(df)} rows, {len(df.columns)} cols</p></body></html>"
    msg.attach(MIMEText(html_body, 'html'))

    csv_data = df.to_csv(index=False)
    attachment = MIMEApplication(csv_data.encode('utf-8'), _subtype='csv')
    attachment.add_header('Content-Disposition', 'attachment', filename=f'{report_title}.csv')
    msg.attach(attachment)

    try:
        context = ssl.create_default_context()
        with smtplib.SMTP('smtp.gmail.com', 587) as server:
            server.starttls(context=context)
            server.login(email_address, email_password)
            server.send_message(msg)
        print(f"✅ '{report_title}' sent to {recipient_email}")
    except Exception as e:
        print(f"❌ Failed: {e}")

def weekly_report_job():
    """Generate and send the weekly report."""
    print(f"[{pd.Timestamp.now()}] Generating weekly report...")
    
    # Simulate fetching/creating your report data
    df = pd.DataFrame({
        'Product': ['A', 'B', 'C', 'D', 'E', 'F'],
        'Sales': [100, 200, 150, 300, 250, 180],
        'Revenue': [1000, 2500, 1800, 3600, 3000, 2160]
    })

    send_report(df, 'recipient@example.com', 'Weekly Sales Report')

# ---- Schedule the job ----
schedule.every().monday.at('09:00').do(weekly_report_job)

print("✅ Scheduler started. Waiting for Monday 9:00 AM...")
print("   (To test now, change schedule to every().minutes.do(...))")

# Keep the script running
while True:
    schedule.run_pending()
    time.sleep(1)  # Check every second

When you run this script, it will sit quietly until Monday at 9:00 AM, then automatically generate and send the report.

Want to test it immediately? Replace the schedule line with:

schedule.every(5).minutes.do(weekly_report_job)

This will send a test report every 5 minutes while you’re debugging.

Production tip: On a Linux server, you can run this script with nohup so it keeps running even if you log out:

nohup python send_report.py &

But Wait — What If Something Goes Wrong?

Email automation fails silently if you don’t handle errors. A temporary network blip, a server timeout, or an expired App Password can cause your report to never arrive — and you might not even know.

Let’s add logging and retries to make the pipeline robust.

import smtplib
import ssl
import os
import time
import logging
import pandas as pd
from email.mime.multipart import MIMEMultipart
from email.mime.text import MIMEText
from email.mime.application import MIMEApplication
from dotenv import load_dotenv

# ---- Set up logging ----
logging.basicConfig(
    level=logging.INFO,
    format='%(asctime)s - %(levelname)s - %(message)s',
    handlers=[
        logging.FileHandler('email_pipeline.log'),  # Log to a file
        logging.StreamHandler()  # Also print to console
    ]
)
logger = logging.getLogger(__name__)

def send_report_with_retry(df, recipient_email, report_title, max_retries=3, delay=5):
    """
    Send a report with automatic retries on failure.
    """
    load_dotenv()
    email_address = os.getenv('EMAIL_ADDRESS')
    email_password = os.getenv('EMAIL_PASSWORD')

    if not email_address or not email_password:
        logger.error("Credentials not found in .env file")
        return False

    # Build the message (same as before)
    msg = MIMEMultipart()
    msg['From'] = email_address
    msg['To'] = recipient_email
    msg['Subject'] = report_title

    html_body = f"""
    <html><body>
    <h2>{report_title}</h2>
    <p>Generated: {pd.Timestamp.now().strftime('%Y-%m-%d %H:%M')}</p>
    <p>{len(df)} rows, {len(df.columns)} columns</p>
    </body></html>
    """
    msg.attach(MIMEText(html_body, 'html'))

    csv_data = df.to_csv(index=False)
    attachment = MIMEApplication(csv_data.encode('utf-8'), _subtype='csv')
    attachment.add_header('Content-Disposition', 'attachment', filename=f'{report_title}.csv')
    msg.attach(attachment)

    # Attempt to send with retries
    for attempt in range(1, max_retries + 1):
        try:
            logger.info(f"Attempt {attempt}/{max_retries}: Connecting to SMTP...")
            context = ssl.create_default_context()
            with smtplib.SMTP('smtp.gmail.com', 587) as server:
                server.starttls(context=context)
                server.login(email_address, email_password)
                server.send_message(msg)
            
            logger.info(f"✅ Report '{report_title}' sent to {recipient_email}")
            return True

        except smtplib.SMTPAuthenticationError:
            logger.error("❌ Authentication failed. Check your App Password.")
            return False  # No point retrying bad credentials
        except Exception as e:
            logger.warning(f"❌ Attempt {attempt} failed: {e}")
            if attempt < max_retries:
                logger.info(f"   Retrying in {delay} seconds...")
                time.sleep(delay)
            else:
                logger.error(f"❌ All {max_retries} attempts failed. Report not sent.")
                return False

# ---- Example usage ----
if __name__ == "__main__":
    df = pd.DataFrame({
        'Product': ['A', 'B', 'C'],
        'Sales': [100, 200, 150],
        'Revenue': [1000, 2500, 1800]
    })

    success = send_report_with_retry(df, 'recipient@example.com', 'Weekly Sales Report')
    if success:
        print("\n✅ Pipeline completed successfully.")
    else:
        print("\n❌ Pipeline failed. Check email_pipeline.log for details.")

If everything works, your log will show:

2025-01-15 09:00:01,001 - INFO - Attempt 1/3: Connecting to SMTP...
2025-01-15 09:00:02,345 - INFO - ✅ Report 'Weekly Sales Report' sent to recipient@example.com

✅ Pipeline completed successfully.

If the SMTP server is temporarily down, you’ll see:

2025-01-15 09:00:01,001 - INFO - Attempt 1/3: Connecting to SMTP...
2025-01-15 09:00:05,234 - WARNING - ❌ Attempt 1 failed: timed out
2025-01-15 09:00:05,234 - INFO -    Retrying in 5 seconds...
2025-01-15 09:00:10,236 - INFO - Attempt 2/3: Connecting to SMTP...
2025-01-15 09:00:11,890 - INFO - ✅ Report 'Weekly Sales Report' sent to recipient@example.com

What this means: Your report will almost never fail silently. If something goes wrong, you’ll know exactly why and where.

Recap: What You Just Built

Let’s look at what you accomplished:

  1. Secure credential handling — Using environment variables and Gmail App Passwords instead of hardcoding secrets.

  2. Message construction with attachments — Building a MIMEMultipart email with both an HTML body (dynamic table) and a CSV file attached.

  3. SMTP sending — Connecting to Gmail’s server via TLS, authenticating, and sending the message.

  4. Scheduling — Using the schedule library to run your report automatically every Monday at 9 AM.

  5. Robust error handling — Adding logging and automatic retries so you always know what’s happening.

This same pattern works for any report — CSV, PDF, HTML, images, or a combination. The send_report() function is reusable across any project.

What’s next? In the next article, we’ll add HTML email templates with inline charts — so your boss gets a beautiful, formatted report, not just a CSV.

Check Your Understanding

Let’s make sure the concepts stick. Try answering these questions based on what you learned.

Remember:

  • What does SMTP stand for, and what does it do in one sentence?

Understand:

  • Why do we use MIMEMultipart instead of just MIMEText when sending a report with an attachment?

Apply:

  • Modify the send_report() function to send the email to three recipients instead of one. (Hint: the ‘To’ header can be a comma-separated string.)

Analyze:

  • Your email sends successfully, but the recipient says the attachment is empty. Where in the pipeline would you start debugging? What would you check first?

Evaluate:

  • Compare using environment variables vs. hardcoding the password. What are the security trade-offs in a team project where multiple people need to run the script?

Create:

  • Design a function that sends a daily summary email with three attachments: a CSV, a PNG chart, and an HTML body with the chart embedded inline. What MIME types would you use for each?
  • ‘Automating ETL Pipelines with Python’ — Learn how to build the data pipeline that generates the reports before you email them.
  • ‘Building Beautiful HTML Reports with Jinja2 and Pandas’ — Create polished HTML email bodies with dynamic tables and inline images.
  • ‘Error Handling and Logging in Python Data Pipelines’ — Go deeper into building robust error handling for production scripts.

Apply What You Learned is for Supporter and Insider subscribers.

Subscribe to unlock the exercises on this post.

See plans
  • Python Engineering Under review

    SQLAlchemy for Data Scientists: Querying Databases Without Raw SQL Strings

    Picture this: You're a data scientist, and you've just spent three hours building a beautiful data pipeline in a Jupyter notebook. You've got your SQL queries working perfectly in your local SQLite database.

  • Python Engineering Under review

    OCR With Tesseract and Python: Turning Images Into Text Data

    You're staring at a scanned PDF of a report, a photo of a restaurant receipt, or a screenshot of a table from a website. The information you need — the numbers, the names, the dates — is *right there* in the image.

  • Python Engineering Under review

    A Data Science Glossary 100 Terms Explained In Pla

    Before we talk about models or metrics, we need to agree on what “data” actually looks like in Python. When you load a CSV file, you’re not staring at raw numbers — you’re staring at a carefully labeled structure.

  • Python Engineering Under review

    Dask for Out-of-Core Data: When Your Dataset Doesn't Fit in Memory

    You’ve just received a 20GB CSV file. Your laptop has 8GB of RAM. You fire up a Jupyter notebook and type `pd.read_csv('huge_file.csv')`. The kernel churns for a few seconds, then you see it: `MemoryError`.

Looking for something else?

Search every article by title, summary or topic.