Send Automated email using SMTP in python.

This article will help you to learn how send personalized emails to a single or group of person using SMTP with some simple lines of python.

Sending an Email is pretty simple to do unless you want to send it to a large group of people at the same time. But what if you want to do so? If you are running a company or an online business or service, you surely want to handle a large number of customers, you might always need to send them emails about the updates, but this is not practically applicable for you to send emails to a large customer group manually. Here python can help you in really cool ways. let's look at how python can help to send emails from your Gmail account to others.

Setting up your Gmail Account.

Before starting, you need to change some settings in your Gmail account. First of all, you want to change the security settings to allow your python code to send messages, so creating a test email account is more suitable and highly recommended. After that, you may want to create an Application password for your Gmail account. Just, go to your google account > Security > App password.

Steps involved:

  1. Setting up an SMTP(Secure Mail Transfer Protocol) server using python.
  2. Login to your Gmail account using your email and password.
  3. Specifying headers like From, To, and Subject using the MIMEMultipart message object.
  4. Add the message
  5. Sending messages using SMTP server.

Setting up an SMTP server.

Using the smtplib package in python you can simply set up an SMTP server with the port number. smtplib is a built-in package in python for sending basic emails without any subject, for sending complete emails we require the email package in python.

import smtplib

# setting the SMTP server with port number
= smtplib.SMTP('smtp.gmail.com',587)

# Starting the server
s.starttls()

# Logging to the Gmail account
s.login(my_email, password)

Log in with your email and the App password created.

Sending an email using python.

Sending a basic email to a specific account is just an easy task.

import smtplib

# setting the SMTP server with port number
= smtplib.SMTP('smtp.gmail.com',587)

# Starting the server
s.starttls()

# Logging to the Gmail account
s.login(my_email, password)

message = "Your message"
  
# sending the mail 
s.sendmail("Your email", "receiver email", message)
  
# quit the session
s.quit()

This will send the message specified to the receiver email.

Sending a mail with From, To, and Subject.

Now you know how to send a basic email using python, but for sending a complete email you'll need to add the From address, To address, and the Subject. To achieve this we require the built-in email package in python. Note that the email package alone will not help you to send emails, you also require smtplib.

import smtplib

# setting the SMTP server with port number
= smtplib.SMTP('smtp.gmail.com',587)

# Starting the server
s.starttls()

# Logging to the Gmail account
s.login(my_email, password)

# Create a message object
msg = MIMEMultipart()

# Setting the parameters for the message
msg['From'] = my_email
msg['To'] = "receiver_email"
msg['Subject'] = "Email using python"

# Persons name
name = "Sidharth"

# Compose the message body
msg.attach(MIMEText("Hello {}, How are you doing?".format(name), 'plain'))

# Send message using SMTP server 
s.send_message(msg)
print("Message sent successfully")

Here we created a message object using MIMEMultipart() and specified the parameters. After that, we composed the message body using the MIMEText() method. Then we send the message as mail using the SMTP server we created earlier. Note that the message we are sending is in plain text.

Output:

Sending Email with HTML content.

Whenever you receive an email from companies or websites you'll find some HTML content like the company logo, font styles, their website links, etc, sending emails with HTML content makes sense because plain text emails are not enough for sending emails of good quality. But the interesting thing is that you can actually send any HTML content as email using python, Let's look at how this can be done.
 
name = "Sidharth"

# Creating HTML content
html = """
<html>
    <body>
        <h1>Hi,</h1>
            <p>
            Subscribe to <a href="https://www.pycodemates.com">PyCodeMates</a> for quality contents related to python, machine learning, data science, etc
            </p>
    </body>
</html>
"""
# Compose the message body
msg.attach(MIMEText("Hello {}, How are you doing?".format(name), 'plain'))
msg.attach(MIMEText(html, 'html'))

# Send message using SMTP server 
s.send_message(msg)
print("Message sent successfully")

Here we just added two things, the HTML content body that includes a "Hi" enclosed in the h1 tag, the website link, and then we attached it to the message object with 'html' as the parameter. This is just basic HTML content, you can add more HTML along with CSS to make it more attractive. By running the code we'll get an output like this:

Sending multiple Emails.

So far we learned how to send emails to a single person with plain and HTML content. Now we are looking at how to send multiple personalized emails. Sending emails to multiple users saves a lot of time than sending it manually to each person. Ok then! how can we do it? well, you know about loops which in programming helps to do something repeatedly actually helps here to achieve the task.

First, let's create a dictionary with the name and emails of the persons you want to send emails to:

persons_list = {
    
    "person1":'[email protected]',
    "person2":'[email protected]',
    "person3":'[email protected]',
    "person4":'[email protected]'
                
    }

Let's loop through each of these names and emails so that we can send it to each person.

for name, email in persons_list.items():
    msg = MIMEMultipart()

    # Setting the parameters for the message
    msg['From'] = my_email
    msg['To'] = email
    msg['Subject'] = "Email using python"

    # Creating HTML content
    html = """
    <html>
        <body>
            <h1>Hi,</h1>
                <p>
                Subscribe to <a href="https://www.pycodemates.com">PyCodeMates</a> for quality contents related to python, machine learning, data science, etc
                </p>
        </body>
    </html>
    """
    # Compose the message body
    msg.attach(MIMEText("Hello {}, How are you doing?".format(name), 'plain'))
    msg.attach(MIMEText(html, 'html'))

    # Send message using SMTP server 
    s.send_message(msg)
    print("Message sent successfully")

This code will send emails to all the people specified in the dictionary, there are lots of other ways rather than creating a dictionary, like creating text files for names and emails, building a pandas data frame to save names and emails, etc. But to keep it simple we can use a dictionary data structure in python.

Here is the complete version of the code:

import smtplib
from email.mime.multipart import MIMEMultipart
from email.mime.text import MIMEText

= smtplib.SMTP('smtp.gmail.com',587)
s.starttls()
s.login("my_email", "password")


persons_list = {"person1":'[email protected]',
               "person2":'[email protected]',
               "person3":'[email protected]'
                }


# Looping through all names and emails
for name, email in persons_list.items():

    # creating message object
    msg = MIMEMultipart()

    # Setting the parameters for the message
    msg['From'] = my_email
    msg['To'] = email
    msg['Subject'] = "Email using python"

    # Creating HTML content
    html = """
    <html>
        <body>
            <h1>Hi,</h1>
                <p>
                Subscribe to <a href="https://www.pycodemates.com">PyCodeMates</a> for quality contents related to python, machine learning, data science, etc
                </p>
        </body>
    </html>
    """
    # Compose the message body
    msg.attach(MIMEText("Hello {}, How are you doing?".format(name), 'plain'))
    msg.attach(MIMEText(html, 'html'))

    # Send message using SMTP server 
    s.send_message(msg)
    print("Message sent successfully")