How to Send Automated Email Messages in Python (original) (raw)

Last Updated : 31 Aug, 2021

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.

Step-by-step Implementation

Step 1: Import the following modules

Python3 `

from email.mime.text import MIMEText from email.mime.image import MIMEImage from email.mime.application import MIMEApplication from email.mime.multipart import MIMEMultipart import smtplib import os

`

Step 2: Let's set up a connection to our email server.

smtp = smtplib.SMTP('smtp.gmail.com', 587) smtp.ehlo() smtp.starttls() smtp.login('YourMail@gmail.com', 'Your Password')

`

Step 3: Now, built the message content.

msg = MIMEMultipart() msg['Subject'] = subject msg.attach(MIMEText(text))

`

Step 4: Let's look at how to attach pictures and multiple attachments.

Attaching Images:

img_data = open(one_img, 'rb').read() msg.attach(MIMEImage(img_data, name=os.path.basename(one_img)))

`

Attaching Several Files:

with open(one_attachment, 'rb') as f: file = MIMEApplication( f.read(), name=os.path.basename(one_attachment) ) file['Content-Disposition'] = f'attachment;
filename="{os.path.basename(one_attachment)}"' msg.attach(file)

`

Step 5: The last step is to send the email.

to = ["klm@gmail.com", "xyz@gmail.com", "abc@gmail.com"] smtp.sendmail(from_addr="Your Login Email", to_addrs=to, msg=msg.as_string()) smtp.quit()

`

Below is the full implementation:

Python3 `

Import the following module

from email.mime.text import MIMEText from email.mime.image import MIMEImage from email.mime.application import MIMEApplication from email.mime.multipart import MIMEMultipart import smtplib import os

initialize connection to our

email server, we will use gmail here

smtp = smtplib.SMTP('smtp.gmail.com', 587) smtp.ehlo() smtp.starttls()

Login with your email and password

smtp.login('Your Email', 'Your Password')

send our email message 'msg' to our boss

def message(subject="Python Notification", text="", img=None, attachment=None):

# build message contents
msg = MIMEMultipart()

# Add Subject
msg['Subject'] = subject  

# Add text contents
msg.attach(MIMEText(text))  

# Check if we have anything
# given in the img parameter
if img is not None:
    
    # Check whether we have the lists of images or not!
    if type(img) is not list:  
      
          # if it isn't a list, make it one
        img = [img] 

    # Now iterate through our list
    for one_img in img:
      
          # read the image binary data
        img_data = open(one_img, 'rb').read()  
        # Attach the image data to MIMEMultipart
        # using MIMEImage, we add the given filename use os.basename
        msg.attach(MIMEImage(img_data,
                             name=os.path.basename(one_img)))

# We do the same for
# attachments as we did for images
if attachment is not None:
    
    # Check whether we have the
    # lists of attachments or not!
    if type(attachment) is not list:
      
          # if it isn't a list, make it one
        attachment = [attachment]  

    for one_attachment in attachment:

        with open(one_attachment, 'rb') as f:
          
            # Read in the attachment
            # using MIMEApplication
            file = MIMEApplication(
                f.read(),
                name=os.path.basename(one_attachment)
            )
        file['Content-Disposition'] = f'attachment;\
        filename="{os.path.basename(one_attachment)}"'
        
        # At last, Add the attachment to our message object
        msg.attach(file)
return msg

Call the message function

msg = message("Good!", "Hi there!", r"C:\Users\Dell\Downloads\Garbage\Cartoon.jpg", r"C:\Users\Dell\Desktop\slack.py")

Make a list of emails, where you wanna send mail

to = ["ABC@gmail.com", "XYZ@gmail.com", "insaaf@gmail.com"]

Provide some data to the sendmail function!

smtp.sendmail(from_addr="hello@gmail.com", to_addrs=to, msg=msg.as_string())

Finally, don't forget to close the connection

smtp.quit()

`

Output:

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.

schedule.every(2).seconds.do(mail)

This will call the function mail every 10 minutes.

schedule.every(10).minutes.do(mail)

This will call the function in every hour.

schedule.every().hour.do(mail)

Calling every day at 10:30 AM.

schedule.every().day.at("10:30").do(mail)

Calling a particular day.

schedule.every().monday.do(mail)

Below is the implementation:

Python3 `

import schedule import time from email.mime.text import MIMEText from email.mime.image import MIMEImage from email.mime.application import MIMEApplication from email.mime.multipart import MIMEMultipart import smtplib import os

send our email message 'msg' to our boss

def message(subject="Python Notification", text="", img=None, attachment=None):

# build message contents
msg = MIMEMultipart()

# Add Subject
msg['Subject'] = subject  

# Add text contents
msg.attach(MIMEText(text))  

# Check if we have anything
# given in the img parameter
if img is not None:

      # Check whether we have the
    # lists of images or not!
    if type(img) is not list:
      
          # if it isn't a list, make it one
        img = [img]  

    # Now iterate through our list
    for one_img in img:
      
          # read the image binary data
        img_data = open(one_img, 'rb').read()  
        
        # Attach the image data to MIMEMultipart
        # using MIMEImage,
        # we add the given filename use os.basename
        msg.attach(MIMEImage(img_data, 
                             name=os.path.basename(one_img)))

# We do the same for attachments
# as we did for images
if attachment is not None:

      # Check whether we have the
    # lists of attachments or not!
    if type(attachment) is not list:
      
          # if it isn't a list, make it one
        attachment = [attachment]  

    for one_attachment in attachment:

        with open(one_attachment, 'rb') as f:
          
            # Read in the attachment using MIMEApplication
            file = MIMEApplication(
                f.read(),
                name=os.path.basename(one_attachment)
            )
        file['Content-Disposition'] = f'attachment;\
        filename="{os.path.basename(one_attachment)}"'
        
        # At last, Add the attachment to our message object
        msg.attach(file)
return msg

def mail():

# initialize connection to our email server,
# we will use gmail here
smtp = smtplib.SMTP('smtp.gmail.com', 587)
smtp.ehlo()
smtp.starttls()

# Login with your email and password
smtp.login('Email', 'Password')

# Call the message function
msg = message("Good!", "Hi there!",
              r"C:\Users\Dell\Downloads\Garbage\Cartoon.jpg",
              r"C:\Users\Dell\Desktop\slack.py")

# Make a list of emails, where you wanna send mail
to = ["ABC@gmail.com",
      "XYZ@gmail.com", "insaaf@gmail.com"]

# Provide some data to the sendmail function!
smtp.sendmail(from_addr="hello@gmail.com",
              to_addrs=to, msg=msg.as_string())

# Finally, don't forget to close the connection
smtp.quit()  

schedule.every(2).seconds.do(mail) schedule.every(10).minutes.do(mail) schedule.every().hour.do(mail) schedule.every().day.at("10:30").do(mail) schedule.every(5).to(10).minutes.do(mail) schedule.every().monday.do(mail) schedule.every().wednesday.at("13:15").do(mail) schedule.every().minute.at(":17").do(mail)

while True: schedule.run_pending() time.sleep(1)

`

Output: