Sending multiple Emails using Python script


Introduction To Sending multiple Emails using Python script

In the blog we discuss about sending multiple emails using python script, to send mail using python we used SMTP library and the module also using the MIME (Multipurpose Internet Mail Extension) 

To send mail first, we need to import the module to send mail.

import smtplib

Here in the module also using the MIME (Multipurpose Internet Mail Extension) module to make it more flexible. Using the MIME header, we can store the sender and receiver information and also some other details.

Sending multiple Emails using Python script 

 # Separately send mail using their mail

import smtplib
from email.mime.multipart import MIMEMultipart
from email.mime.text import MIMEText
from email.mime.base import MIMEBase 
from email import encoders 

#The mail addresses and  password
sender_address =’Enter Sender Mail ID’                  
sender_pass =’Enter Sender Password’                                       

# list of reciver email_id to the mail 
li = ['','','']                                                         
#[item for item in input("Enter Receiver Mail Address :- ").split()] this is used to take user input of receiver mail id

# getting length of list 
length = len(li) 
# Iterating the index 
# same as 'for i in range(len(list))' 

# Here we iterate the loop and send msg one by one to the reciver
for i in range(length): 
    X = li[i]
    reciver_mail = X
    message = MIMEMultipart()
    message['From'] = sender_address
    message['To'] =  reciver_mail             #  Pass Reciver Mail Address
    message['Subject'] =  'Mail using python'       #The subject line

    mail_content = '''Hello,
    This is a simple mail. There is file attachments in the mail, The mail is sent using Python SMTP library.
    Thank You'''

    #The body and the attachments for the mail
    message.attach(MIMEText(mail_content, 'plain'))
    #Create SMTP session for sending the mail
    # open the file to be sent  
    filename = ‘File name with extension’                                                    #str(input('Enter File Name With Extension To Attchment :- '))

    # Open PDF file in binary mode
    # The file is in the directory same as where you run your Python script code from 
    with open(filename, "rb") as attachment:
        # MIME attachment is a binary file for that content type "application/octet-stream" is used
        part = MIMEBase("application", "octet-stream")
    # encode into base64 

    part.add_header('Content-Disposition', "attachment; filename= %s" % filename) 

    # attach the instance 'part' to instance 'message' 

    s = smtplib.SMTP('', 587) 
    s.login(sender_address, sender_pass) 
    text = message.as_string()
    s.sendmail(sender_address, reciver_mail, text) 

    print('Mail Sent')

# It Send Separated Mail one by one each receiver mail 

And in this code also given the attachment code file like INvoice PDF Excel Video or some other file etc.

Following are Example code for Attachment of Html file and Decorated Mail 

Widget not in any sidebars

Attractive mail with attachment of HTML file 

# Import  required libraries

import smtplib
import ssl
from email.mime.text import MIMEText
from email.utils import formataddr
from email.mime.multipart import MIMEMultipart  # New line
from email.mime.base import MIMEBase  # New line
from email import encoders  # New line

# User configuration
sender_email = 'Enter Sender Mail id'
sender_name = 'Enter name of sender'
password = 'Enter Sender mail password'

receiver_emails = ['Pass reciver mail address']
receiver_names = ['pass reciver name']

# Email body
email_html = open('Pass HTML File name with Extenstion ')   #Example:- open('Classy.html')
email_body =       # Read HTML File 

filename = 'Enter file name with Extenstion'

for receiver_email, receiver_name in zip(receiver_emails, receiver_names):
        print("Sending the email...")
        # Configurating user's info
        msg = MIMEMultipart()
        msg['To'] = formataddr((receiver_name, receiver_email))
        msg['From'] = formataddr((sender_name, sender_email))
        msg['Subject'] = 'Hello, My Friend ' + receiver_name
        msg.attach(MIMEText(email_body, 'html'))

        # Open PDF file in binary mode
            with open(filename, "rb") as attachment:
                    part = MIMEBase("application", "octet-stream")
            # Encode file for ASCII character.

            # Add header to the email as key/value pair to attachment part
                    f"attachment; filename= {filename}",

        except Exception as e:
                print(f'Oh no! We didn\'t found the attachment!\n{e}')

                # Creating a SMTP session use 587 with TLS for gmail port.
                server = smtplib.SMTP('', 587)
                # Encrypts the email
                context = ssl.create_default_context()
                # We log in into our Google account
                server.login(sender_email, password)
  # from sender, to receiver with the email attachment of html body
                server.sendmail(sender_email, receiver_email, msg.as_string())
                print('Email sent!')
        except Exception as e:
                print(f'Oh no! Something bad happened!\n{e}')
                print('Closing the server...')

Widget not in any sidebars


In this Blog, you get a better idea about how to send multiple mail using SMTP library in python.


Please enter your comment!
Please enter your name here