Send Email using SMTP in Python
In this tutorial, we gonna show you how you can send an email using the Simple Mail Transfer Protocol(SMTP) in python.
How to send email in Python using SMTP?
Before jumping to the code you should know what is SMTP protocol actually. If you know already that’s great. Here is a short definition of SMTP.
SMTP – Simple mail transfer protocol
SMTP is a transport layer protocol. It provides the facility to send the e-mail and routing e-mail between the mail server.
In Python, there is a package smtplib that has SMTP client object that can be used to send the mail.
Now we have to import the smtplib Python package:
Import smtplib package in Python
Now we have to follow the following steps to send the mail in Python:
- Establish an SMTP connection using smtp.gmail.com as an SMTP server.
- use port no. 587.
- Identify client with ehlo() method.
- start transport layer security to encode the message.
- use the login() method by Gmail credential.
- call sendmail() method.
- you have to go on your browser and type :
and click OFF .so it will be ON.
Server setting for gmail in Python smtplib library
Identify the computer system and transport layer security:
user email and password:
firstname.lastname@example.org' password='your password'
Now pass username and password to login function and send mail:
mail.login(username,password) mail.sendmail(username,'email@example.com','Subject:Email \n\n Hello this is an email ') mail.quit()
Now we are going to see the complete Python program:
Example Python program to send email using the gmail SMTP
import smtplib mail=smtplib.SMTP('smtp.gmail.com',587) mail.ehlo() mail.starttls() firstname.lastname@example.org' password='your password' mail.login(username,password) mail.sendmail(username,'email@example.com','Subject:Email \n\n Hello this is an email ') mail.quit() print("successfully sent email please check your gmail.............")
You need to replace it with your SMTP and email credentials as well as the email where you want to send SMS.
The output will be:
successfully sent email, please check your gmail...........
Now you can open the email and check it. If everything goes right then you will get a message to the email:
Hello this is an email
If not please check again and follow instructions correctly it will definitely work.