How to Send Periodic Emails
Wouldn't it be great if you could automate the process of sending emails at specific times daily, weekly, or monthly for your company?
By using Python's schedule
package, you can create a program that performs tasks repeatedly at specific times.
To install the schedule package on your computer, you can run the following command in your terminal:
pip install schedule
In this lesson, we will learn how to use Python to automatically send periodic emails.
Python Packages for Sending Periodic Emails
Using both the schedule package and the smtplib package together, you can automate the task of sending emails at specific times.
Example of a Simple Python Code
Here is an example code that automatically sends an email at 9:00 AM daily.
import schedule
import time
import smtplib
from email.mime.text import MIMEText
from email.mime.multipart import MIMEMultipart
def send_email():
# Setting up sender and receiver information
sender_email = "your_email@example.com"
receiver_email = "receiver@example.com"
password = "your_password"
# Drafting the email's subject and body
subject = "Daily Report"
body = "Hello,\n\nHere is today's daily report.\n\nThank you."
# Setting up MIME
msg = MIMEMultipart()
msg['From'] = sender_email
msg['To'] = receiver_email
msg['Subject'] = subject
msg.attach(MIMEText(body, 'plain'))
# Sending the email
try:
server = smtplib.SMTP('smtp.example.com', 587) # Setting up SMTP server and port
server.starttls() # Starting TLS for security
server.login(sender_email, password) # Logging in
server.sendmail(sender_email, receiver_email, msg.as_string()) # Sending email
print("Email has been sent successfully!")
except Exception as e:
print(f"Error occurred while sending email: {e}")
finally:
server.quit() # Closing the server connection
# Sending email every day at 9:00 AM
schedule.every().day.at("09:00").do(send_email)
# Running the scheduler
while True:
schedule.run_pending()
time.sleep(1)
Code Explanation
1. Setting Time with the Schedule Package
Using the schedule package, you set the send_email
function to run at a specific time.
In the code example above, the email is set to be sent every day at 9:00 AM with the line schedule.every().day.at("09:00").do(send_email)
.
-
every()
: Set the scheduler -
day.at("09:00")
: Executes every day at 9:00 AM -
do(send_email)
: Executes thesend_email
function
2. Running the Scheduler
while True:
schedule.run_pending()
time.sleep(1)
Finally, use a while True
loop to keep the scheduler running continuously.
The schedule.run_pending()
method checks if there is a scheduled task to execute and runs it if available.
The time.sleep(1)
command makes sure that the check occurs every second without wasting CPU resources.
By leveraging schedule
and smtplib
, you can automate periodic email tasks, handling repetitive email work with a program.
Note: In this lesson, we provide only code examples to prevent misuse of email scheduling. You can create a Python program that periodically sends emails and apply it in real life by following projects on CodeFriends Projects.
Want to learn more?
Join CodeFriends Plus membership or enroll in a course to start your journey.