x

Unlock Offer - Flat 50% Off On All Courses

Hide

How to Send Unlimited Bulk Emails using Python? - Codegnan

Published by Kirandeep Kaur | Oct. 15, 2020, 2:08 p.m. | 345 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 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 smtp.gmail.com. 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

Gmail

smtp.gmail.com

Outlook.com/Hotmail.com

smtp-mail.outlook.com

Yahoo Mail

smtp.mail.yahoo.com

AT&T

smpt.mail.att.net (port 465)

Comcast

smtp.comcast.net

Verizon

smtp.verizon.net (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

Gmail

imap.gmail.com

Outlook.com/Hotmail.com

imap-mail.outlook.com

Yahoo Mail

imap.mail.yahoo.com

AT&T

imap.mail.att.net

Comcast

imap.comcast.net

Verizon

incoming.verizon.net

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('smtp.gmail.com', 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("you@gmail.com", "target@example.com", 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 = "you@gmail.com"

toaddr = "target@example.com"

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('smtp.gmail.com', 587)

server.ehlo()

server.starttls()

server.ehlo()

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')

server.set_debuglevel(True) 

#show communication with the server

try:

    dhellmann_result = server.verify('dhellmann')

    notthere_result = server.verify('notthere')

finally:

    server.quit()

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='smtp.gmail.com:587'):

    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)

    server.starttls()

    server.login(login,password)

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

    server.quit()

Example Usage of above script

sendemail(from_addr    = contact@codegnan.com', 

          to_addr_list = ['codegnan@gmail.com'],

          cc_addr_list = ['codegnan@xx.co.in'], 

          subject      = 'Hello', 

          message      = 'Hello from a python function', 

          login        = 'pythonuser', 

          password     = 'XXXXX')

Sample Email Received

sendemail(from_addr    = 'python@RC.net', 

          to_addr_list = ['RC@gmail.com'],

          cc_addr_list = ['RC@xx.co.uk'], 

          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.
 
The next(reader) line skips the header row, so that the next line for the reader's name, email, grade: breaks subsequent rows at each comma, and preserves the resulting values for the current contact's name, email, and grade strings. If the values in your CSV file contain whitespace on one or both sides, you can use the.strip() method to erase them.
 

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.

 

 

 

 

 

Tags:

Trending Blogs