Daily email reports - Python Script

 

Python Programming Language: A Versatile Journey from Beginner to Expert

 

Python script to send daily email reports, and how to set it up for automation. We'll use the smtplib library to send the emails and email.mime for constructing the email content. For scheduling, we'll use a cron job on Unix-like systems or Task Scheduler on Windows.

Step 1: Create the Python Script

  1. Install Required Libraries:

    bash
    pip install yagmail

  2. Write the Script:

    python
    
    import yagmail
    import datetime
    
    def generate_report():
        # Generate or load your report here. This is just an example.
        return "This is your daily report for " + str(datetime.date.today())
    
    def send_email_report():
        # Email configuration
        sender = '[email protected]'
        receiver = '[email protected]'
        subject = 'Daily Report'
        content = generate_report()
    
        # Initialize the yagmail.SMTP object
        yag = yagmail.SMTP(user=sender, password='your_password')
    
        # Send the email
        yag.send(
            to=receiver,
            subject=subject,
            contents=content,
        )
        print("Email sent successfully!")
    
    if __name__ == "__main__":
        send_email_report()
    

Step 2: Schedule the Script

On Unix-like Systems using Cron

  1. Open the Crontab File:

    bash
    crontab -e
    
  2. Add a Cron Job: Add the following line to schedule the script to run daily at a specific time (e.g., 8 AM):

    bash
    0 8 * * * /usr/bin/python3 /path/to/your_script.py

    Save and exit the crontab editor.

On Windows using Task Scheduler

  1. Open Task Scheduler.
  2. Create a New Basic Task.
    • Name: Daily Email Report
    • Trigger: Daily
    • Start time: 8:00 AM (or your preferred time)
  3. Action:
    • Start a Program.
    • Program/script: python
    • Add arguments: C:pathtoyour_script.py
  4. Finish the task setup.

Step 3: Ensure Security

  • Environment Variables: Store sensitive information like email passwords in environment variables rather than hardcoding them in the script.

    python
    
    import os
    import yagmail
    import datetime
    
    def generate_report():
        return "This is your daily report for " + str(datetime.date.today())
    
    def send_email_report():
        sender = os.getenv('EMAIL_USER')
        password = os.getenv('EMAIL_PASSWORD')
        receiver = '[email protected]'
        subject = 'Daily Report'
        content = generate_report()
    
        yag = yagmail.SMTP(user=sender, password=password)
    
        yag.send(
            to=receiver,
            subject=subject,
            contents=content,
        )
        print("Email sent successfully!")
    
    if __name__ == "__main__":
        send_email_report()
    
  • Set Environment Variables:

    • On Unix-like systems, add the following lines to your .bashrc or .zshrc:
      bash
      export EMAIL_USER='[email protected]'
      export EMAIL_PASSWORD='your_password'
      
      Then, reload the shell configuration:
      bash
      export EMAIL_USER='[email protected]'
      export EMAIL_PASSWORD='your_password'
      
    • On Windows, add environment variables through the System Properties -> Environment Variables interface.

Step 4: Testing

Run the script manually to ensure it works:

bash
python /path/to/your_script.py

Check your inbox to confirm the email was sent correctly.

This setup ensures that your daily report is generated and sent automatically every day at the specified time. If you encounter any issues, make sure to check the logs and error messages for troubleshooting.