How to Send Automated Email Messages in Python
In this article, we are going to see how to send automated email messages which involve delivering text messages, essential photos, and important files, among other things. in Python.
We’ll be using two libraries for this: email, and smtplib, as well as the MIMEMultipart object. This object has multiple subclasses; these subclasses will be used to build our email message.
- MIMEText: It consists of simple text. This will be the body of the email.
- MIMEImage: This would allow us to add images to our emails.
- MIMEAudio: If we wish to add audio files, we may do it easily with the help of this subclass.
- MIMEApplication: This can be used to add anything or any other attachments.
Step 1: Import the following modules
Step 2: Let’s set up a connection to our email server.
- Provide the server address and port number to initiate our SMTP connection
- Then we’ll use smtp.ehlo to send an EHLO (Extended Hello) command.
- Now, we’ll use smtp.starttls to enable transport layer security (TLS) encryption.
Step 3: Now, built the message content.
- Assign the MIMEMultipart object to the msg variable after initializing it.
- The MIMEText function will be used to attach text.
Step 4: Let’s look at how to attach pictures and multiple attachments.
- First, read the image as binary data.
- Attach the image data to MIMEMultipart using MIMEImage, we add the given filename use os.basename
Attaching Several Files:
- Read in the attachment using MIMEApplication.
- Then we edit the attached file metadata.
- Finally, add the attachment to our message object.
Step 5: The last step is to send the email.
- Make a list of all the emails you want to send.
- Then, by using the sendmail function, pass parameters such as from where, to where, and the message content.
- At last, just quit the server connection.
Below is the full implementation:
Schedule Email Messages
For scheduling the mail, we will make use of the schedule package in python. It is very lightweight and easy to use.
Install the module
pip install schedule
Now look at the different functions that are defined in a schedule module and their use:
The below function will call the function mail every 2 seconds.
This will call the function mail every 10 minutes.
This will call the function in every hour.
Calling every day at 10:30 AM.
Calling a particular day.
Below is the implementation: