Javatpoint Logo
Javatpoint Logo

Python Sending Email using SMTP

Sending Mail Transfer Protocol (SMTP) is used as a protocol to handle the email transfer using python. It is used to route emails between email servers.

Python provides smtplib module, which defines an SMTP client session object used for the purpose of sending emails to an internet machine. For this purpose, we have to import the smtplib module using the import statement.

The SMTP object is used for the email transfer. The following syntax is used to create the smtplib object.

It accepts the following parameters.

  • host: It is the hostname of the machine which is running your SMTP server. Here, we can specify the IP address of the server like ( or localhost. It is an optional parameter.
  • port: It is the port number on which the host machine is listening to the SMTP connections. It is 25 by default.
  • local_hostname: If the SMTP server is running on your local machine, we can mention the hostname of the local machine.

The sendmail() method of SMTP object is used to send the mail to the desired machine. The syntax is given below.


Sending email from gmail

There are the cases where the emails are sent using gmail SMTP server. In this case, we can pass gmail as the SMTP server instead of using localhost with the port 587.

Use the following syntax.

Here, we need to login to the gmail account using gmail user name and password. For this purpose, the smtplib provide the login() method which accepts the username and password of the sender.

Consider the following example.


Sending HTML in email

We can format the HTML in the message by specifying the MIME version, content-type, and character set to send the HTML.

Consider the following example.


Next Topic#

Help Others, Please Share

facebook twitter pinterest

Learn Latest Tutorials


Trending Technologies

B.Tech / MCA