SMTP protocol client in Python (smtplib)

PythonProgrammingServer Side Programming

Python's standard library has 'smtplib' module which defines an SMTP client session object that can be used to send mail via Python program.

A mail server is an application that handles and delivers e-mail over the internet. Outgoing mail servers implement SMTP, or Simple MailTransfer Protocol, servers which are an Internet standard for email transmission.

Incoming mail servers come in two main varieties. POP3, or Post office protocol and IMAP, or Internet Message Access Protocol.


This function returns an object of SMTP class. It encapsulates and manages a connection to an SMTP or ESMTP server. Following arguments are defined in the signature of this function −

A string which is the name of the remote host to which to connect.  
A number that specifies the port to which to connect. By default, smtplib.SMTP_PORT is used.  
used as the FQDN of the local host in the HELO/EHLO command.  
  a 2-tuple (host, port) object to which the socket to bind

It has the following methods that support SMTP operations −

connect() −

This method establishes a connection to a host on a given port.

login() −

This function takes username and password arguments to login to SMTP server.

quit() −

This function terminates SMTP session.

data() −

The 'message' argument to this function is sent to server.


This function sends a command and returns its response code

ehlo() −

This function identifies the server.

starttls() −

This function starts TLS mode.

getreply() −

This function receives reply from the server in the form of response code.

putcmd() −

This function sends a command to the server.

send_message() −

This function converts the message to a byte string and passes it to send mail.

sendmail() −

This command performs an entire mail transaction.

The arguments are −

 The address sending this mail.
 A list of addresses to send this mail to.  
 The message to send.

Code below uses smtp server of gmail to send an email. The SMTP object uses gmail's smtp server at  port 527. The ehlo() command identifies the server. We also activate Transport Layer Security to the outgoing mail message.

Next, the login() command is invoked by passing credentials as arguments toit. Finally the mail message is assembled by attaching it a header in the prescribed format and it is sent using sendmail() method. The SMTP object is closed afterward.

import smtplib
mail.sendmail(sender,recipient, content)

Before running above script, ensure that sender's gmail account is provided access to 'less secure apps'.

Set the shown toggle button to ON.

Execute above script after performing above setting. The message should be delivered to recipient's inbox.

Published on 16-Jan-2019 17:51:36