How to Send Email in Python SMTP - Python Tutorial | Logic Practice
Python Course / Web Development / How to Send Email in Python SMTP

How to Send Email in Python SMTP

BLUF: This lesson on How to Send Email in Python SMTP provides a comprehensive guide to understanding and implementing this concept in Python. Whether you're a beginner or looking to refresh your knowledge, you'll find clear explanations and interactive code examples here.
Key Concept: How to Send Email in Python SMTP

Mastering How to Send Email in Python SMTP is essential for building efficient Python applications. Focus on the syntax and the best practices highlighted in this tutorial.

The Simple Mail Transfer Protocol (SMTP) serves as a protocol for managing email transfer through Python. This protocol is responsible for directing emails between various email servers. Operating at the application layer, it enables users to send messages to one another. Recipients access their emails utilizing either the POP (Post Office Protocol) or IMAP (Internet Message Access Protocol).

When the server is set to receive a TCP connection from a client, it starts the connection process on port 587.

Python includes a module named smtplib, which establishes an SMTP client session object that facilitates the sending of emails to an external internet server. To utilize this functionality, it is necessary to import the smtplib module through the import statement.

Example

$ import smtplib

The SMTP class is utilized for the purpose of transferring emails. The subsequent syntax is employed to instantiate the smtplib object.

Example

import smtplib

smtpObj = smtplib.SMTP(host, port, local_hostname)

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 ( https://www.logic-practice.com ) 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 SMTP object's sendmail function is utilized to dispatch email to the specified machine. Below is the syntax for this method.

Example

smtpObj.sendmail(sender, receiver, message)

Python Example for Sending Email using SMTP

Let’s consider an example to illustrate the process of sending an email utilizing SMTP in Python.

Example

#!/usr/bin/python3

import smtplib

sender_mail = '[email protected]'

receivers_mail = ['[email protected]']

message = """From: From Person %s

To: To Person %s

Subject: Sending SMTP e-mail

This is a test e-mail message.

"""%(sender_mail,receivers_mail)

try:

   smtpObj = smtplib.SMTP('localhost')

   smtpObj.sendmail(sender_mail, receivers_mail, message)

   print("Successfully sent email")

except Exception:

   print("Error: unable to send email")

Sending Email from Gmail

There are scenarios in which emails are dispatched utilizing the Gmail SMTP server. In such instances, we have the option to specify Gmail as the SMTP server rather than employing localhost on port 587.

To send an email using Gmail, the following syntax must be employed.

Example

$ smtpObj = smtplib.SMTP("gmail.com", 587)

In this instance, it is essential to access the Gmail account utilizing the Gmail username along with the password. To facilitate this, the smtplib module offers the login function, which requires the sender's username and password as its parameters.

This could prompt your Gmail account to request permission for access to less secure applications, provided you are utilizing Gmail. You will need to enable this feature temporarily for the process to function correctly.

Python Example to Send Email from Gmail

To illustrate how to send an email using Gmail in Python, let's consider an example.

Example

#!/usr/bin/python3

import smtplib

sender_mail = '[email protected]'

receivers_mail = ['[email protected]']

message = """From: From Person %s

To: To Person %s

Subject: Sending SMTP e-mail

This is a test e-mail message.

"""%(sender_mail,receivers_mail)

try:

   password = input('Enter the password');

   smtpObj = smtplib.SMTP('gmail.com',587)

   smtpobj.login(sender_mail,password)

   smtpObj.sendmail(sender_mail, receivers_mail, message)

   print("Successfully sent email")

except Exception:

   print("Error: unable to send email")

Sending HTML in Email

To format the HTML within the message, it is essential to indicate the MIME version, content-type, and character set to effectively transmit the HTML.

Python Example to Send HTML in Email

Let us consider an example to illustrate the process of sending HTML content via email using Python.

Example

#!/usr/bin/python3

import smtplib

sender_mail = '[email protected]'

receivers_mail = ['[email protected]']

message = """From: From Person %s

To: To Person %s

MIME-Version:1.0

Content-type:text/html

Subject: Sending SMTP e-mail

<h3>Python SMTP</h3>

<strong>This is a test e-mail message.</strong>

"""%(sender_mail,receivers_mail)

try:

   smtpObj = smtplib.SMTP('localhost')

   smtpObj.sendmail(sender_mail, receivers_mail, message)

   print("Successfully sent email")

except Exception:

   print("Error: unable to send email")

Input Required

This code uses input(). Please provide values below:

Logic Practice
Install Logic Practice
Add to home screen for a faster app-like experience