What is SMTP?

SMTP is a protocol that is used to send emails, and as we know Python provides the ‘smtplib’ library to interact with it. Being by importing the library and establishing a connection with your email server. Below are the following steps to send mails:

Step 1: First of all, “smtplib” library needs to be imported.

Step 2: After that create a session, we will be using its instance SMTP to encapsulate an SMTP connection.

s = smtplib.SMTP('smtp.gmail.com', 587)

Step 3: In this, you need to pass the first parameter of the server location and the second parameter of the port to use. For Gmail, we use port number 587.

Step 4: For security reasons, now put the SMTP connection in TLS mode. TLS (Transport Layer Security) encrypts all the SMTP commands. After that, for security and authentication, you need to pass your Gmail account credentials in the login instance. The compiler will show an authentication error if you enter an invalid email id or password.

Step 5: Store the message you need to send in a variable say, message. Using the sendmail() instance, send your message. sendmail() uses three parameters: sender_email_id, receiver_email_id and message_to_be_sent. The parameters need to be in the same sequence.

Code Implementation:

This will send the email from your account. After you have completed your task, terminate the SMTP session by using quit(). 

Python3




import smtplib
# creates SMTP session
s = smtplib.SMTP('smtp.gmail.com', 587)
# start TLS for security
s.starttls()
# Authentication
s.login("sender_email_id", "sender_email_id_password")
# message to be sent
message = "Message_you_need_to_send"
# sending the mail
s.sendmail("sender_email_id", "receiver_email_id", message)
# terminating the session
s.quit()


Send Emails Using Python

By using Python, you can send emails which can be a valuable skill for automation, communication, and data-driven processes. In this article, we will explore how to send mail from Gmail using Python.

Similar Reads

How can you send Emails using Python?

Python offers a library to send emails- “SMTP” Library. “smtplib” creates a Simple Mail Transfer Protocol (SMTP) client session object which is used to send emails to any valid Email ID on the internet....

What is SMTP?

SMTP is a protocol that is used to send emails, and as we know Python provides the ‘smtplib’ library to interact with it. Being by importing the library and establishing a connection with your email server. Below are the following steps to send mails:...

Send Email to Multiple Recipients using Python

...