Your essential guide to the world of Artificial Intelligence. The AI Journal delivers daily news, in-depth analysis, and expert insights on machine learning and beyond.

Breaking

Thursday, 23 October 2025

How Do I Automatically Email My Daily Sales Report with Python?

How Do I Automatically Email My Daily Sales Report with Python?


 How Do I Automatically Email My Daily Sales Report with Python?

You've done the hard work. You've set up your systems, and your sales data is being collected. You even followed our Goodbye, Messy Data...  guide to write a script that automatically cleans your messy CSV files. But now you're stuck in a new loop: every morning, you have to manually open that cleaned_sales.csv file to see what's happening.

This is a classic automation bottleneck. The final step in any good data pipeline isn't just collecting data; it's delivering the insights to the people who need them.

What if you could wake up, check your phone, and see a perfectly formatted email with your key sales numbers already in your inbox? Today, I’ll show you exactly how to build a simple, powerful Python script that does just that.

 Your Toolkit: What You'll Need

This entire script runs on free, standard Python libraries.

  1. Python: Installed on your computer.

  2. Pandas Library: We used this in our last data post. If you don't have it, install it with pip install pandas.

  3. A Gmail/Google Account: This script is configured for Gmail's SMTP server, which is free and reliable.

  4. A Google App Password: (CRITICAL STEP) You cannot use your regular Google password in a script. We'll cover this next.

A Vital Security Lesson: Why You Need a "Google App Password"

In the past, people would hard-code their main Gmail password directly into scripts. This is an extremely dangerous security risk. If anyone ever saw your code, they would have full access to your entire Google account.

To fix this, Google created App Passwords. An App Password is a 16-digit passcode that gives a specific app (like our Python script) permission to access your Google Account without you having to share your real password.

How to Create Your App Password

  1. Go to your Google Account settings: myaccount.google.com

  2. Go to Security.

  3. Ensure 2-Step Verification is turned ON. You cannot create an App Password unless this is active.

  4. Under "Signing in to Google," click on App Passwords.

  5. You'll be prompted to sign in again.

  6. Under "Select app," choose "Other (Custom name)".

  7. Name it something you'll remember, like "My Daily Sales Script", and click Generate.

  8. Google will give you a 16-character password (e.g., xxxx xxxx xxxx xxxx). Copy this password immediately. This is what you will paste into your script.

 The Automation Script: From CSV to Email

Now for the fun part. Let's write the code. This script will perform three main tasks:

  1. Read our cleaned_sales.csv using Pandas.

  2. Calculate a simple summary (like total sales and total units sold).

  3. Format that summary into a beautiful HTML email and send it.

 Step 1: Import Libraries and Set Credentials

First, we import the libraries and set up our sensitive credentials.

Python
import pandas as pd
import smtplib
from email.mime.text import MIMEText
from email.mime.multipart import MIMEMultipart

# --- Your Credentials ---
# IMPORTANT: Use your App Password here, NOT your real password
SENDER_EMAIL = "your-email@gmail.com"
SENDER_PASSWORD = "your-16-digit-app-password"
RECIPIENT_EMAIL = "your-email@gmail.com"
# --- End of Credentials ---

 Step 2: Read and Analyze Data with Pandas

Next, we'll use Pandas to read the clean CSV file we created in our previous tutorial and generate a quick summary.

Python
# Read the cleaned CSV data
try:
    df = pd.read_csv('cleaned_sales.csv')
except FileNotFoundError:
    print("Error: 'cleaned_sales.csv' not found. Make sure the file is in the same directory.")
    exit()

# Perform some basic analysis
total_sales = df['Price'].sum()
total_units_sold = df['Quantity'].sum()
average_order_value = df['Price'].mean()

# Create a small summary DataFrame
summary_data = {
    'Metric': ['Total Sales', 'Total Units Sold', 'Average Order Value'],
    'Value': [f"${total_sales:,.2f}", f"{total_units_sold}", f"${average_order_value:,.2f}"]
}
summary_df = pd.DataFrame(summary_data)

 Step 3: Format the Email Content (The HTML Trick)

This is the secret to making your email look professional. Instead of sending boring plain text, we can convert our Pandas DataFrame directly into an HTML table.

Python
# Create the email message
message = MIMEMultipart("alternative")
message["Subject"] = "Your Daily Sales Report"
message["From"] = SENDER_EMAIL
message["To"] = RECIPIENT_EMAIL

# Create the HTML for the email
html_body = f"""
<html>
  <head>
    <style> 
      body {{ font-family: 'Arial', sans-serif; }}
      table {{ border-collapse: collapse; width: 60%; }}
      th, td {{ border: 1px solid #dddddd; text-align: left; padding: 8px; }}
      th {{ background-color: #f2f2f2; }}
    </style>
  </head>
  <body>
    <h2>Good Morning!</h2>
    <p>Here is your daily sales summary for {pd.to_datetime('today').strftime('%Y-%m-%d')}:</p>
    
    {summary_df.to_html(index=False)}
    
    <p>Have a great day!</p>
  </body>
</html>
"""

# Attach the HTML body to the email
message.attach(MIMEText(html_body, "html"))

 Step 4: Connect to the Server and Send

Finally, this block of code securely connects to Google's SMTP server using your App Password and sends the email.

Python
# Send the email
try:
    # Connect to the Gmail SMTP server
    server = smtplib.SMTP_SSL('smtp.gmail.com', 465)
    server.ehlo()
    
    # Log in using your App Password
    server.login(SENDER_EMAIL, SENDER_PASSWORD)
    
    # Send the email
    server.sendmail(SENDER_EMAIL, RECIPIENT_EMAIL, message.as_string())
    
    # Close the connection
    server.close()
    
    print("Email sent successfully!")

except Exception as e:
    print(f"Error: Unable to send email. {e}")

Taking It to the Next Level: True Automation

You now have a script you can run to send a report. But the final step is to make it run automatically. You don't even want to have to click "run."

You can use your computer's built-in tools for this:

  • On Windows: Use Task Scheduler to set the your_script.py file to run every day at a specific time (e.g., 7 AM).

  • On macOS/Linux: Use Cron (a time-based job scheduler) to set the same daily schedule.

By creating this script, you've officially built a three-stage automated data pipeline: your data is cleaned, analyzed, and delivered, allowing you to focus on growing your business.

No comments:

Post a Comment

Search This Blog

Popular Posts

THE AI JOURNAL