New Year Offer - Flat 50% Off On All Courses


How to Send Unlimited Bulk Emails using Python? - Codegnan

Last updated on Nov. 17, 2020, 2:10 p.m. 1 Views



He is a tech-expert with 7 years of industrial experience in Python, Data Analysis, Big Data, Machine Learning and NLP. He has 360 degrees of expertise in all these subjects. He is known for his practical approach to different real-time industrial problems. He is known for his great interest in helping students reach their true potential and scale greater heights. Believing in Problem-based teaching pedagogies, he left his job in Malaysia as a data engineer and came back to the newly born state to fill the void between students and the industry.

How to Send Unlimited Bulk Emails using Python? - Codegnan

Last updated on Nov. 17, 2020, 2:10 p.m. 1 Views




Sending Email

To check and reply to the emails is a big-time draining. Obviously, you cannot write a program to handle all your emails because each email requires its own response. But if you know how to write programs that can send and receive emails, you can also automate loads of email-related activities.

Example, you might have a spreadsheet having details of customer records and you want to send each customer a personalized message. Commercial software might be able to do this for you but it will charge you more. In such cases, you can write your own program to send these personalized emails, saving yourself a lot of time copying and pasting form emails.

Several computer programs can even notify you of things when you are away from your computer. You don't want to return to your machine every few minutes to check the state of the program while you're automating a process that takes a couple of hours to complete. Instead, when it's finished, the software will only text your number, allowing you to work on more meaningful items while you are away from your device. Isn’t it a good deal?

SMTP in Python

SMTP determines how to format, encrypt and send email messages between mail servers, and all the other information that your system manages after you have pressed Send. However, you do not need to know this technical information, since the smtplib module from Python simplifies them into a few functions. 

SMTP works with only sending emails to everyone. A separate protocol, called IMAP, deals with email retrieval sent to you and is defined in IMAP.

smtplib Overview

The smtplib module defines an SMTP client session object that can be used to send mail to any Internet machine with an SMTP or ESMTP listener daemon. SMTP stands for Simple Mail Transfer Protocol.0020. The smtplib module is useful for communicating with mail servers to send mail. Sending mail is done with Python’s smtplib using an SMTP server. Actual usage varies depending on the complexity of the email and settings of the email server, the instructions here are based on sending email through Gmail.

Connecting to a SMTP Server

You may be familiar with configuring the SMTP server and connection if you've ever set up Thunderbird, Outlook, or another program to link to your email address. For each email service, these configurations may be different, but a site search for < your service > smtp configurations can bring up the server and port to be used.

The SMTP account domain name will generally be the name of the domain name of your email provider, with smtp. Gmail's SMTP server, for instance, is at Some popular email providers and their SMTP servers are listed below. (The port is an integer value and will almost always be 587, which is used by the TLS standard for order encryption.)


Provider SMTP server domain name
Yahoo Mail
AT&T (port 465)
Verizon (port 465)

Create an SMTP object by calling smptlib.SMTP(), passing the domain name as a string argument, and passing the port as an integer argument until you have the domain name and port information for your email provider. The SMTP object represents an SMTP mail server link and has email sending methods.

Connecting to IMAP Server

Just when you need an SMTP object to link and send emails to an SMTP server, you need an IMAPClient object to link and receive emails from an IMAP server. Next, you'll need the IMAP server domain name for your email provider. It would be different from the domain name of the SMTP server. For many popular email providers, the table below lists the IMAP servers.

Provider IMAP server domain name
Yahoo Mail
AT&T 465)

Once you have the domain name of the IMAP server, call the imapclient.IMAPClient() function to create an IMAPClient object. Most email providers require SSL encryption, so pass the ssl=True keyword argument.

smtplib Usage

Firstly, create an SMTP object and each object is used for connection with one server.

	import smtplib

	server = smtplib.SMTP('', 587)

	#Next, log in to the server

	server.login("youremailusername", "password")

	#Send the mail

	msg = "Hello!" # The /n separates the message from the headers

	server.sendmail("", "", msg)

If you want to include a From, To and Subject headers, use the email package because smtplib does not modify the contents or headers at all.

Email Package Overview

Python’s email package contains many classes and functions for composing and parsing email messages.

Email Package Usage

We’ll start by only importing only the classes we need; this also saves us from having to use the full module name later.

	from email.MIMEMultipart import MIMEMultipart

	from email.MIMEText import MIMEText

Then compose some of the basic message headers:

fromaddr = ""

toaddr = ""

msg = MIMEMultipart()

msg['From'] = fromaddr

msg['To'] = toaddr

msg['Subject'] = "Python email"

Next, attach the body of the email to the MIME message:

body = "Python test mail"

msg.attach(MIMEText(body, 'plain'))

For sending the mail, we must convert the object to a string, and then use the same procedure as above to send using the SMTP server.

import smtplib

server = smtplib.SMTP('', 587)




server.login("youremailusername", "password")

text = msg.as_string()

server.sendmail(fromaddr, toaddr, text)

Verify an email address

The SMTP protocol includes a command to ask a server whether an address is valid. Usually, VRFY is disabled to prevent spammers from finding legitimate email addresses, but if it is enabled you can ask the server about an address and receive a status code indicating validity along with the user’s full name.

import smtplib

server = smtplib.SMTP('mail')


#show communication with the server


    dhellmann_result = server.verify('dhellmann')

    notthere_result = server.verify('notthere')



print 'dhellmann:', dhellmann_result

print 'notthere :', notthere_result

Sending Mails using Gmail

import smtplib

def sendemail(from_addr, to_addr_list, cc_addr_list,subject, message,login, password,smtpserver=''):

	header  = 'From: %s' % from_addr

	header += 'To: %s' % ','.join(to_addr_list)

	header += 'Cc: %s' % ','.join(cc_addr_list)

	header += 'Subject: %s' % subject
	message = header + message
	server = smtplib.SMTP(smtpserver)

	problems = server.sendmail(from_addr, to_addr_list, message)

Example Usage of above script

sendemail(from_addr    =', 

          to_addr_list = [''],

          cc_addr_list = [''], 

          subject      = 'Hello', 

          message      = 'Hello from a python function', 

          login        = 'pythonuser', 

          password     = 'XXXXX')

Sample Email Received

sendemail(from_addr    = '', 

          to_addr_list = [''],

          cc_addr_list = [''], 

          subject      = 'Howdy', 

          message      = 'Howdy from a python function', 

          login        = 'pythonuser', 

          password     = 'XXXXX')

Sending multiple emails (sending bulk emails)

The code example below shows you how to open a CSV file and loop (skipping the header row) over its content lines. We have printed Sending Email to ... to make sure the coding works properly before you send emails to all your contacts. For each touch, which we can later substitute with features that send emails:

import csv
with open("contacts_file.csv") as file:
    reader = csv.reader(file)
    next(reader)  # Skip header row
    for name, email, grade in reader:
        print(f"Sending email to {name}")
        # Send email here

As per the above example, using with open(filename) as file: ensures that the file closes at the end of the code block. csv.reader() makes reading a CSV file line by line and extracting its values fast.


Helpful links

Sending bulk emails through Django

How to Send Automated Emails with Python

Final Words

With this blog, you are now aware to start a secure SMTP connection and send personalized bulk emails to the people in your email list. If you are stuck in any problem while writing code, you could contact us. Our Python experts will help you get rid of any problem. Enjoy sending emails with Python.






Trending Certifications at Codegnan

Python for Data Science Certification



MTA Certification - Python for Data Science

555 Learners

200 Hours

Next Batch:
4th Jan | Weekday (Online) | 07:00PM - 09:00PM

Key Skills:
Mathematical Thinking, Critical Thinking

Machine Learning with Python Certification



Codegnan Certification for Machine Learning

431 Learners

50 Hours

Next Batch:
Nov 23rd | Weekday (Online) | 10:00AM - 12:00PM

Key Skills:
Mathematical thinking, Python Programming Skills

Web Development with Python - Django Certification



Codegnan Certification for Django

380 Learners

40 Hours

Next Batch:
Dec 1st | Weekday (Online) | 6:00PM - 7:00PM

Key Skills:
Python Programming Skills

ReactJS Certification



Codegnan Certification for ReactJs

98 Learners

60 Hours

Next Batch:
Nov 30th | Weekday (Online) | 2:00PM - 4:00PM

Key Skills:
HTML, CSS, Java Script

Become a Certified Professional  


Video Reviews