How to send multiple emails simple way using python

Using python send an 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.

For 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 Email

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 an 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

Gmail

Outlook.com/Hotmail.com

Yahoo Mail

AT&T

Comcast

Verizon

SMTP server domain name

smtp.gmail.com

smtp-mail.outlook.com

smtp.mail.yahoo.com

smpt.mail.att.net(port 465)

smtp.comcast.net

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

Gmail

Outlook.com/Hotmail.com

Yahoo Mail

AT&T

Comcast

Verizon

IMAP server domain name

imap.gmail.com

imap-mail.outlook.com

imap.mail.yahoo.com

imap.mail.att.net

imap.comcast.net

incoming.verizon.net

Once you have the domain name of the IMAP server, call the IMAP client.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 smtplibserver = 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 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)

Email Package Usage

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 an email using python

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 an email here

As per the above example, using open(filename) as a 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

Helpful links

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.

If you are planning to learn Python or looking for a lucrative career in Python or data science, then get back to us for the head to toe training in Python. We, at Codegnan, have a full-fledged Python MTA certification training module for the upcoming Pythonists where they will gain an understanding of Python and you will be able to solve logical problems quickly. You will understand the working of various Python libraries like SciPy, NumPy, Matplotlib, Lambda function, etc., and avail them to futureproof your career in various domains of Python like Data Science, Machine Learning, and Artificial Intelligence.

Do you know how much a Python developer earns in India? A Python developer in India earns around 427,293 INR to 1,150,000.What are you waiting for then? A lucrative and futureproof career in Python is waiting for you! Get back to us, we’ll help you merge with other expert Pythonists.