Python

Python script to automate sending daily email reports

To automate sending daily email reports in Python, you can use the smtplib and email modules. The smtplib module defines an SMTP client session object that can be used to send mail to any internet machine with an SMTP or ESMTP listener daemon. The email module is used to construct email messages.

Here’s a basic script to automate sending daily email reports:

import smtplib
from email.mime.text import MIMEText
from email.mime.multipart import MIMEMultipart
import datetime

# Email configuration
email_from = 'your_email@example.com'
email_to = 'recipient_email@example.com'
smtp_server = 'smtp.example.com'
smtp_port = 587
smtp_username = 'your_smtp_username'
smtp_password = 'your_smtp_password'

# Create message
msg = MIMEMultipart()
msg['From'] = email_from
msg['To'] = email_to
msg['Subject'] = 'Daily Report - ' + datetime.datetime.now().strftime('%Y-%m-%d')

# Add message body
message = 'This is your daily report. Insert your report content here.'
msg.attach(MIMEText(message, 'plain'))

# Connect to SMTP server and send email
try:
    server = smtplib.SMTP(smtp_server, smtp_port)
    server.starttls()
    server.login(smtp_username, smtp_password)
    text = msg.as_string()
    server.sendmail(email_from, email_to, text)
    server.quit()
    print('Email sent successfully!')
except Exception as e:
    print('Failed to send email. Error:', e)

To set it up:

  1. Replace 'your_email@example.com' with your email address and 'recipient_email@example.com' with the recipient’s email address.
  2. Replace 'smtp.example.com' with your SMTP server address, 587 with the SMTP port (587 is the default for TLS), and 'your_smtp_username' and 'your_smtp_password' with your SMTP username and password.
  3. Customize the message body as needed.
  4. Schedule the script to run daily using a task scheduler like cron (Linux/Mac) or Task Scheduler (Windows). For example, to run the script every day at 8 AM, you can use the following cron entry:
0 8 * * * /path/to/python3 /path/to/your_script.py

Ensure you have the necessary permissions to run the script and that your SMTP server allows sending emails using the provided credentials.