Home »
Python
Sending Emails using SMTP in Python
Python | Sending emails: In this tutorial, we are going to learn how to send emails in Python using SMTP (smtplib library)?
Submitted by Abhinav Gangrade, on July 04, 2020
Library:
smtplib
SMTP is a simple mail transfer protocol used by the email servers to categorize the emails and deliver them to the clients.
smtplib:
smtplib is a python library that creates an SMTP session to send emails and route the mails.
Steps to send emails using SMTP
1) Create a SMTP Server:
We can create an SMTP server with the help of smtplib.SMTP("smtp.gmail.com",587), smtp.gmail.com is the Gmail SMTP server address and 587 is the port number of the server.
2) To identify our server:
We can identify our server with the help server.elho() function, we should do this connection to our server with other servers to send mails.
3) Make our server secure:
We can make our server secure with the help of the server.starttls(), TLS is Transport Layer Security.
4) Login in our server:
As we will use the Gmail SMTP server so we can log in to the server with the help of the server.login("<email id>","<password>").
5) Send the mail:
We can send the mail with the help of server.sendmail(<Our mail address>,<To we want to send>, message) function.
6) server.close():
After sending the close the server with this function.
Python program to send email
# import the library
import smtplib
# setting up the Gmail smtp server
server=smtplib.SMTP("smtp.gmail.com",587)
# Identify our server before sending mail
server.ehlo()
# making our server secure
server.starttls()
# login in the server
server.login("<email id>","<password>")
# sending mail
message="Hello This is Abhinav Gangrade,how are you"
server.sendmail("<your mail id","<To whom you want to send>",message)
# closing the server
server.close()
Note: You have to change the setting of your Gmail (Less secure app to on).Otherwise, we will not be able to send mails this is because we created a virtual server, and google security will not allow anyone to login to its server so that's why we have to change the setting.