When You Combine Scattered Technologies, They Become a Money-Printing Machine

In previous chapters, we mastered three independent magical technologies:

  1. Python Web Scraping: Able to visit competitors' websites and extract all product prices.
  2. Pandas Data Analysis: Can calculate average prices and highest/lowest prices in seconds.
  3. Data Visualization: Transforms these cold numbers into beautiful bar charts that even your boss can understand.

If your boss asks you to create a report "right now," you can run these three scripts in 5 minutes and submit it.
But what if your boss says: "This report is great! Starting today, I want the latest report on my desk every morning at 8 AM!"

Are you really going to set an alarm, wake up at 7:50 AM every day, and manually execute the scripts?
Of course not. A true Vibe Coder assembles these scripts into a "fully automated super bot" that works for you 24/7 on a cloud server.


The Ultimate Mashup: Writing a "Self-Emailing" Integrated Script

Today, we’ll ask AI to help us write a "mega-fusion" Python script.
This script will execute the following steps in sequence: scrape data → calculate averages → generate charts → and finally, automatically send an email with the chart attached to your boss's inbox!

This involves Python’s core email-sending modules: smtplib and email.
To send emails in Python, the recommended approach is to use Gmail’s SMTP server. However, you must first enable "App Password" in your Google Account settings—never store your real Gmail login password in the code!

【Fully Automated Email Report Prompt】
I’ve already written scrape_laptops() (scraping function) and draw_price_chart() (charting function, which outputs price_compare.png).
Please help me write a function named send_report_email with the following requirements:

  1. Use Python’s smtplib and email packages to send an email via Gmail.
  2. Set the email subject to: "📊 Daily Market Trends: Gaming Laptop Competitor Price Analysis Report".
  3. Include a professional report introduction in the email body.
  4. Most critical step: Attach the generated price_compare.png image file to the email.
  5. After sending, print "✅ Report successfully sent to the boss's inbox!".
  6. Package the complete email logic with Chinese comments.

AI-Generated Auto-Email Script:

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

def send_report_email():
    # Your Gmail account and newly created "App Password"
    # (In practice, these should be stored in a .env file—here for demo purposes)
    sender_email = "your_email@gmail.com"
    sender_password = "your_app_password"
    receiver_email = "boss@company.com"

    # 1. Create the email base (subject, sender, recipient)
    msg = MIMEMultipart()
    msg['Subject'] = "📊 Daily Market Trends: Gaming Laptop Competitor Price Analysis Report"
    msg['From'] = sender_email
    msg['To'] = receiver_email

    # 2. Write the email body and attach it
    body_text = """
    Good morning, Boss:
    
    Here is today's (2024) latest gaming laptop competitor price analysis report.  
    We've scraped the latest prices from three major e-commerce platforms and generated average price bar charts for each brand.  
    
    See the attached file (price_compare.png) for detailed charts.  
    
    Best regards,  
    Vibe Data Analytics Team  
    """
    msg.attach(MIMEText(body_text, 'plain', 'utf-8'))

    # 3. Attach the image file
    file_path = 'price_compare.png'
    if os.path.exists(file_path):
        with open(file_path, 'rb') as file:
            attachment = MIMEApplication(file.read(), _subtype="png")
            attachment.add_header('Content-Disposition', 'attachment', filename=file_path)
            msg.attach(attachment)
    else:
        print("🚨 Image file not found—attachment skipped!")
        return

    # 4. Log in to Google's SMTP server and send the email!
    try:
        # Use Google's SMTP server (Port 587 for TLS encryption)
        server = smtplib.SMTP('smtp.gmail.com', 587)
        server.starttls()  # Enable encryption
        server.login(sender_email, sender_password)
        server.send_message(msg)
        server.quit()  # Close connection after sending
        
        print(f"✅ Report successfully sent to the boss's inbox ({receiver_email})!")
    except Exception as e:
        print(f"🚨 Email failed to send: {e}")

# ==========================================
# The Grand Finale: One-Click Execution
# ==========================================
if __name__ == "__main__":
    print("🤖 Launching daily report bot...")
    # scrape_laptops()    # Run scraper
    # draw_price_chart()  # Generate charts
    send_report_email()   # Send the email!

Making It Truly "Automatic": Crontab and GitHub Actions

Now the script works perfectly, but we’re one step away from "making it run automatically at 8 AM daily."

You have two mainstream options:

  1. Old-School Engineer’s Romance (Crontab): If you have an always-on old laptop or rent a Linux server (e.g., AWS), use the system’s crontab command:
    0 8 * * * python3 /path/to/your/script.py
    This magical line means: "Every day at 08:00, the system will automatically execute this Python script."
  2. Modern Cloud Mastery (GitHub Actions): The ultimate zero-cost, no-computer-required solution.
    Push your Python script to GitHub, then create a .github/workflows/schedule.yml config file in your repo.
    Tell GitHub: "Every morning at 8 AM, spin up a free virtual machine, install Python, install dependencies, and run this email script for me!"

Congratulations! After these 5 lessons, you’ve evolved from a data novice into a top-tier data engineer capable of building a "fully automated business intelligence system"!
The future belongs to data, and now, the key to unlocking its treasure trove is firmly in your hands. Onward to your next AI project!

Unlock Full Tutorial

This chapter is paid content. Join the project to unlock over 5000 words of deep analysis, including 10+ god-tier Prompts and real Source Code examples!