Sending multiple Emails using Python script

0
6238

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 = ['recivermail1@gmail.com','recivermail2@gmail.com','recivermail3@gmail.com']                                                         
#[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
    
    print(reciver_mail)
    
    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")
        part.set_payload(attachment.read())
    # encode into base64 
    encoders.encode_base64(part) 

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

    # attach the instance 'part' to instance 'message' 
    message.attach(part) 


    s = smtplib.SMTP('smtp.gmail.com', 587) 
    s.starttls() 
    s.login(sender_address, sender_pass) 
    text = message.as_string()
    s.sendmail(sender_address, reciver_mail, text) 
    s.quit() 

    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 = email_html.read()       # 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'))

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

            # Add header to the email as key/value pair to attachment part
            part.add_header(
                    "Content-Disposition",
                    f"attachment; filename= {filename}",
            )

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

        try:
                # Creating a SMTP session use 587 with TLS for gmail port.
                server = smtplib.SMTP('smtp.gmail.com', 587)
                # Encrypts the email
                context = ssl.create_default_context()
                server.starttls(context=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}')
                break
        finally:
                print('Closing the server...')
                server.quit()


Widget not in any sidebars

Conclusion

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

LEAVE A REPLY

Please enter your comment!
Please enter your name here