Have you ever wanted to create a Python script for sending daily email reports? Ok, admittedly not many of us need such a specific productivity hack – but if you don’t mind a little bit of coding, try our method.
We’ll break this into a few key steps:
- Write the Python Script: This script will use Python’s
smtplib
andemail
libraries to send an email. - Set up the Email Content: The script will include a function to generate or specify the content you want to send.
- Schedule the Script: We’ll use a task scheduler to run the script automatically every day. For Windows, we can use Task Scheduler, and for Linux/Mac, we can use
cron
.
Step 1: Writing the Python Script
First, let’s write a Python script that sends an email. This script will use Gmail as the SMTP server, but you can modify the SMTP settings to match your email provider.
import smtplib
from email.mime.text import MIMEText
from email.mime.multipart import MIMEMultipart
def send_email(subject, message, to_email):
from_email = 'your_email@gmail.com'
from_password = 'your_password'
# Set up the MIME
msg = MIMEMultipart()
msg['From'] = from_email
msg['To'] = to_email
msg['Subject'] = subject
# Attach the message to the MIME
msg.attach(MIMEText(message, 'plain'))
# Create SMTP session for sending the mail
server = smtplib.SMTP('smtp.gmail.com', 587) # use gmail with port
server.starttls() # enable security
server.login(from_email, from_password) # login with mail_id and password
text = msg.as_string()
server.sendmail(from_email, to_email, text)
server.quit()
print("Email sent successfully.")
# Example usage
subject = "Daily Report"
message = "Here is your daily report..."
to_email = "recipient_email@example.com"
send_email(subject, message, to_email)
Important Security Note: Hardcoding your password in a script can be insecure. Consider using environment variables or encrypted secrets management solutions for better security.
Step 2: Email Content Setup
Modify the message
variable in the script to load or generate your report. You might want to integrate with another Python script or database to fetch the latest data.
Step 3: Scheduling the Script
On Windows systems:
- Open Task Scheduler.
- Create a Basic Task:
- Name the task and provide a description.
- Set the trigger to daily.
- Set the action to “Start a Program”. Point it to your Python executable and provide the script’s path as an argument.
On Linux/Mac platforms:
- Edit your crontab by running
crontab -e
in your terminal. - Add a new line in the following format to run it at, say, 8 AM daily:
0 8 * * * /usr/bin/python3 /path/to/your_script.py
Replace /usr/bin/python3
and /path/to/your_script.py
with the actual path to your Python executable and your script.
Conclusion
And that’s it! Your Python script is now set up to send daily email reports. Make sure to test it to ensure everything works as expected, and adjust your SMTP settings as necessary depending on your email provider.