Learning Python Network Programming

(Sean Pound) #1

Engaging with E-mails


Lots of other things also happen en-route, and then the mail reaches the recipient's
local e-mail gateway. Then, the recipient can retrieve the e-mail by using his or her
e-mail client.


A few protocols are involved in the aforementioned process. The most common of
those have been listed here:



  • Simple Mail Transfer Protocol (SMTP): The SMTP protocol is used by the
    MTA for delivering your e-mail to the recipient's e-mail server. The SMTP
    protocol can only be used for sending e-mails from one host to another.

  • Post Office Protocol 3 (POP3): The POP3 protocol provides a simple and
    standardized way for the users to gain access to the mailboxes and then
    download the messages to their computers. When using the POP3 protocol,
    your e-mail messages will be downloaded from the Internet service
    provider's (ISP) mail server to the local computer. You can also leave the
    copies of your e-mails on the ISP server.

  • Internet Message Access Protocol (IMAP): The IMAP protocol also provides
    a simple and standardized way for accessing your e-mail from the ISP's local
    server. IMAP is a client/server protocol in which the e-mails are received
    and held for you by your ISP. As this requires only a small data transfer,
    this scheme works well even over a slow connection, such as the mobile
    phone network. Only if you send a request to read a specific e-mail, that
    email message will be downloaded from the ISP. You can also do some other
    interesting things, such as creating and manipulating folders or mailboxes on
    the server, deleting messages, and so on.


Python has three modules, smtplib, poplib, and imaplib, which support
SMTP, POP3, and the IMAP protocols respectively. Each module has options for
transmitting the information securely by using the Transport Layer Security (TLS)
protocol. Each protocol also uses some form of authentication for ensuring the
confidentiality of the data.


Sending e-mails with SMTP


We can send an e-mail from a Python script by using smtplib and e-mail packages.
The smtplib module provides an SMTP objects which is used for sending mail by
using either an SMTP or an Extended SMTP (ESMTP) protocol. The e-mail module
helps us in constructing the e-mail messages with the help of the various header
information and attachments. This module conforms to the Internet Message Format
(IMF) described at http://tools.ietf.org/html/rfc2822.html.

Free download pdf