Sending Emails With Python

Janvi Kumari Last Updated : 12 Jun, 2024
4 min read

Introduction

This article offers a detailed guide on automating email sending using Python‘s `smtplib` library. It covers setting up an environment, generating sample data, and creating basic line plots. It also discusses advanced customization options like line styles, colors, and markers for visually appealing visualizations. The guide also teaches how to annotate plots and save them as image files. This article is suitable for those new to Python or looking to enhance data visualization skills.

Overview

  • Learn how to install necessary libraries and set up Python for email automation.
  • Understand how to use smtplib to send emails to a single recipient, including authentication and session management.
  • Explore methods for sending emails to multiple recipients using Python and smtplib.
  • Explore customization options for email content and formatting, and learn how to handle exceptions and errors in email sending.

Why Use Python for Sending Emails?

Python is simple and its readability makes it an excellent choice for automation which includes sending emails. When we need to send regular updates, notification or marketing emails, Python can make this process time saving.

For sending emails with Python we will be using SMTP which also stands for Simple Mail Transfer Protocol. This protocol is used to send emails across the Internet. This Library “smtplib” creates a client session object which can be used to send to any valid Email ID . The SMTP server operates on port 25, but for secure transmission, port 587 is used.

Before starting, you must have Python already installed on your system. And you need access to an email account with SMTP credentials. Most of the email providers give these credentials such as Gmail or Outlook.

Let’s see the steps of this now:

  • First, you need to import the smtplib library.
  • Now create a session.
  • In this, you need to pass the parameter of the server location and the port the first parameter should be the server location and then port. For Gmail , we use port number 587.
  • for security purpose, now put the SMTP connection inTSL(Transport Layer Security) mode. After this , for security and authentication, you need to pass your Gmail account credentials in the login instance.
  • Now store the message you need to send in variable, message and using the sendmail() instance  send your message with the three parameters in the sequence.

Send Email Single Recipient

Send email from your to single Recipient’s account using Python.

With Python, you may use the smtplib package to send an email to a single recipient. This library allows you to send emails via the SMTP. This method works well for automating sending alerts, notifications, or customized messages. To send an email to a single recipient, authenticate, and set up an SMTP session, see the following snippet of code.

Send Email Single Recipient
#import csvimport smtplib
server= smtplib.SMTP(‘smtp.gmail.com’,587)
server.starttls()
server.login(‘sender_email_id’,’sender_email_password”)
message=”Message to be sent”
server.sendmail(‘sender_email_id”,”receiver_email”,message)
server.quit()

Send Email to Multiple Recipients

Now, Let’s see how to Send email to Multiple Recipients using Python.

If the same email needs to be send to different person. For loop can be used for that. Let’s see this with an example

import smtplib
list_of_email=[‘[email protected]’,’[email protected]’]
for i in list_of_email:
	server= smtplib.SMTP(‘smtp.gmail.com’,587)
server.starttls()
server.login(‘sender_email_id’,’sender_email_password”)
message=”Message to be sent”
server.sendmail(‘sender_email_id”,i,message)
server.quit()

Sending email with Attachment from Gmail Account

Now we will explore the code on how we can send email with attachment from Gmail account.

Sending email with Attachment from Gmail Account
#Libraries to import
import smtplib
from email.mime.text import MIMEText
from email.mime.multipart import MIMEMultipart
from email.mime.base import MIMEBase
from email import encoders

from_email_add= “Email ID of sender”
to_email_add=”Email ID of receiver”

#instance of MIMEMultipart
msg= MIMEMultipart()

msg[‘from’]=from_email_add
msg[‘to’]=to_email_add
msg[‘subject’]=”Subject of the mail”
body=”Body of the mail”

#attach the body with the msg instance
msg.attach(MIMEText(body,’plain’))

#open the file to be sent
filename=”file_with_the_extension”
attachment=open(“Path of the file”,”rb”)

#instance of MIMEBase and named as server
q=MIMEBase(‘application’,’octet-stream’)

#To change the payload into encoded form
q.set_payload((attachment).read())

#encode into base64
encoders.encode_base64(server)

q.add_header(‘Content-Disposition’,’attachment; filename=%s” % filename)

#attach the instance ‘server’ to instance ‘msg’
msg.attach(q)

#creates SMTP session
server= smtplib.SMTP(‘smtp.gmail.com’,587)

server.starttls()
server.login(from_email_add,”Password of the sender”)
#Converting the Multipart msg into a string
text=msg.as_string()

#sending the mail
server.sendmail(from_email_add,to_email_add,text)
#terminate the session
server.quit()

In this as well you can use  loop for sending it to multiple people. This code might not work it two step verification on you Gmail account is enabled 

Conclusion

Automating email sending tasks is simple and efficient with Python’s smtplib package. Python’s SMTP protocol and ease of use make it a flexible option for sending messages to one or more recipients, as well as including attachments. Python is a great tool for a variety of applications, from marketing campaigns to notifications, as it streamlines communication procedures and saves time when automating email activities.

Frequently Asked Questions

Q1. What is smtplib in Python?

A. The smtplib Python library is used to send emails using SMTP. It provides a convenient way to send emails programmatically from your Python application.

Q2. What are SMTP credentials?

A. SMTP credentials are the username and password used to authenticate and connect to an SMTP server. You need these credentials to send emails via SMTP.

Q3. Can I send emails with attachments using smtplib?

A. It is possible to send emails with attachments using smtplib. You can attach files to email messages by attaching them to MIMEMultipart messages after encoding them as Base64 strings.

Hi, I am Janvi, a passionate data science enthusiast currently working at Analytics Vidhya. My journey into the world of data began with a deep curiosity about how we can extract meaningful insights from complex datasets.

Responses From Readers

Clear

Congratulations, You Did It!
Well Done on Completing Your Learning Journey. Stay curious and keep exploring!

We use cookies essential for this site to function well. Please click to help us improve its usefulness with additional cookies. Learn about our use of cookies in our Privacy Policy & Cookies Policy.

Show details