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:
- Setting up an SMTP(Secure Mail Transfer Protocol) server using python.
- Login to your Gmail account using your email and password.
- Specifying headers like From, To, and Subject using the MIMEMultipart message object.
- Add the message
- 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 numbers = smtplib.SMTP('smtp.gmail.com',587)# Starting the servers.starttls()# Logging to the Gmail accounts.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 numbers = smtplib.SMTP('smtp.gmail.com',587)# Starting the servers.starttls()# Logging to the Gmail accounts.login(my_email, password)message = "Your message"# sending the mails.sendmail("Your email", "receiver email", message)# quit the sessions.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 numbers = smtplib.SMTP('smtp.gmail.com',587)# Starting the servers.starttls()# Logging to the Gmail accounts.login(my_email, password)# Create a message objectmsg = MIMEMultipart()# Setting the parameters for the messagemsg['From'] = my_emailmsg['To'] = "receiver_email"msg['Subject'] = "Email using python"# Persons namename = "Sidharth"# Compose the message bodymsg.attach(MIMEText("Hello {}, How are you doing?".format(name), 'plain'))# Send message using SMTP servers.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 contenthtml = """<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 bodymsg.attach(MIMEText("Hello {}, How are you doing?".format(name), 'plain'))msg.attach(MIMEText(html, 'html'))# Send message using SMTP servers.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 = {}
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 messagemsg['From'] = my_emailmsg['To'] = emailmsg['Subject'] = "Email using python"# Creating HTML contenthtml = """<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 bodymsg.attach(MIMEText("Hello {}, How are you doing?".format(name), 'plain'))msg.attach(MIMEText(html, 'html'))# Send message using SMTP servers.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 smtplibfrom email.mime.multipart import MIMEMultipartfrom email.mime.text import MIMETexts = smtplib.SMTP('smtp.gmail.com',587)s.starttls()s.login("my_email", "password")}# Looping through all names and emailsfor name, email in persons_list.items():# creating message objectmsg = MIMEMultipart()# Setting the parameters for the messagemsg['From'] = my_emailmsg['To'] = emailmsg['Subject'] = "Email using python"# Creating HTML contenthtml = """<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 bodymsg.attach(MIMEText("Hello {}, How are you doing?".format(name), 'plain'))msg.attach(MIMEText(html, 'html'))# Send message using SMTP servers.send_message(msg)print("Message sent successfully")