How to use python for Daily Email reports automation ?

Email automation

Sending daily email reports in Python requires one to set up his environment to do so. Here is a step-by-step process:

How to use python for Daily Email reports automate ?


Step 1: Setting Up the Environment


Installation of the Required Libraries:

smtplib: This library is used by Python to send emails via SMTP. It comes pre-installed.

email: This also is a native Python library that will help in formatting your emails.

Optionally, if your report is in a file, say CSV or PDF, then you may use pandas along with similar libraries to generate content and os for file attachments.


Install any external libraries using pip where appropriate:

pip install pandas


Email Account Setup:

You need an email account that will allow access via SMTP. Most Gmail accounts do this but you will need to enable "Less secure apps" or use an App Password.


Step 2: Scripting

Below, please find a sample Python script that does send a daily email reporting automation:



import smtplib
import os
from email.mime.multipart import MIMEMultipart
from email.mime.text import MIMEText
from email.mime.base import MIMEBase
from email import encoders
from datetime import datetime

def send_email(subject, body, to_email, from_email, smtp_server, smtp_port, login, password, attachment_path=None):
    # Create a multipart message
    msg = MIMEMultipart()
    msg['From'] = from_email
    msg['To'] = to_email
    msg['Subject'] = subject

    # Attach the body with the msg instance
    msg.attach(MIMEText(body, 'plain'))

    # Attach file if provided
    if attachment_path:
        attachment = open(attachment_path, "rb")

        # Instance of MIMEBase and named as p
        part = MIMEBase('application', 'octet-stream')

        # To change the payload into encoded form
        part.set_payload((attachment).read())

        # Encode into base64
        encoders.encode_base64(part)

        # Add header with pdf name
        part.add_header('Content-Disposition', f"attachment; filename= {os.path.basename(attachment_path)}")

        # Attach the instance 'part' to instance 'msg'
        msg.attach(part)

    # Create SMTP session for sending the mail
    try:
        server = smtplib.SMTP(smtp_server, smtp_port)
        server.starttls()  # Secure the connection
        server.login(login, password)  # Login with your email account

        # Convert the Multipart msg into a string
        text = msg.as_string()

        # Send the mail
        server.sendmail(from_email, to_email, text)

        # Close the server connection
        server.quit()

        print("Email sent successfully!")

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

def generate_daily_report():
    # Placeholder function where you generate your daily report
    # For example, you could generate a CSV, read from a database, etc.
    # Here, we simply return a string
    return "This is your daily report."

if __name__ == "__main__":
    # Email details
    to_email = "recipient@example.com"
    from_email = "your-email@example.com"
    smtp_server = "smtp.example.com"
    smtp_port = 587
    login = "your-email@example.com"
    password = "your-password"

    # Report details
    subject = f"Daily Report - {datetime.now().strftime('%Y-%m-%d')}"
    body = generate_daily_report()
    attachment_path = "/path/to/your/report.csv"  # Optional: path to your report file

    # Send the email
    send_email(subject, body, to_email, from_email, smtp_server, smtp_port, login, password, attachment_path)



STAGE 3: Comments to the script


SMTP setup:

smtplib.SMTP connect to the SMTP server

starttls() - encrypt the connection

login() - log in to the email server


Email creation:

MIMEMultipart() - contain file along with text

MIMEText Add plain text in the email body

MIMEBase, and encoders.encode_base64()- To encode and attach files


Email sending:

sendmail() sends the mail through the SMTP server.

Finally, the server is closed with server.quit().


Attaching Files

You can attach a file- be it a report, generated daily, for example.



Step 4: Scheduling the Script

You can schedule this script to run every day using a scheduler.


On Linux:

You may use cron for running this script at a given time:

crontab -e


You would add one line something like this to run it at 8 in the morning each day:

0 8 * * * /usr/bin/python3 /path/to/your/script.py



In Windows:

  • Use the Task Scheduler:
  • Create a new task.
  • Set the Trigger as Daily at whatever time you want.
  • Set the Action to start the Python script.


Step 5: Testing of the Script

Before scheduling, test the script by running it manually to ensure the emails are going through as they should be. Ensure the SMTP server, email, and password match.

The following script is a simple, yet versatile solution for your daily automated emailing and reporting. You can make it even further tailored to your needs by adding such functionality as advanced report generation, better error handling, or multiple recipients.

Post a Comment

0 Comments