Everything About Python IMAP | imaplib module

Email automation helps large companies find your audience and engage with their customers. Instead of wasting time and resources on manual campaigns, you can let automation do the job and other valuable tasks. With automation, you can send personalized emails to influential individuals like essential clients. Python’s imaplib helps you create such automation.

IMAP, which stands for Internet Mail Access Protocol, is an email retrieval protocol. It reads, sends, or displays them. This is very useful in low bandwidth conditions.

Why do we need this Module?

Python’s client-side library called imaplib is used for accessing emails over the mentioned IMAP protocol. It encapsulates a connection to an IMAP4 server and implements a large subset of the IMAP4rev1 client protocol defined in RFC 2060.

Module Hierarchy

Python-imaplib

This module defines three classes, IMAP4, IMAP4_SSL, and IMAP4_stream. IMAP4 is the base class where IMAP4_SSL and IMAP4_stream are derived classes of IMAP4.

  • IMAP4 – Uses clear text sockets.
  • IMAP4_SSL – Uses encrypted communication techniques over SSL sockets
  • IMAP4_stream – Makes use of standard input and output of external commands.

Importing the Module

As of Python 3.10, it’s part of the Python Standard Library under the Internet Protocols and Support category.

import imaplib

IMAP Basic Commands

To understand this module, you must have a general understanding of basic IMAP commands.

CommandDescription
IMAP_LOGINThis command initiates a connection between IMAP and the protocol.
CAPABILITYThis command requests a list of server compatible capabilities
NOOPThis command acts as a notification system for new messages or status updates during inactivity.
SELECTAllows us to select a mailbox’s inbox to access the messages.
EXAMINESimilar to SELECT in function, but does not allow any changes to the messages.
CREATEUsed to create a new mailbox and assign its name.
DELETEUsed to delete a mailbox of the given name.
RENAMEAllows to change the name of a mailbox
LOGOUTInforms the protocol that it is done with the session and proceeds to close all connections.

Using imaplib to Login to Gmail in Python and retrieve Emails

In the following code, we will be using Python imaplib to access a Gmail inbox and display emails. You can try this code out yourself using our online compiler.

import imaplib
import pprint

imapHost = 'imap.gmail.com'
imapUser = '[email protected]'
imapPasscode = 'password'

# connecting to host via SSL
imap = imaplib.IMAP4_SSL(imapHost)

# logging in to servers
imap.login(imap_user, imap_pass)

# Selecting the inbox of the logged in account
imap.select('Inbox')


tmp, data = imap.search(None, 'ALL')
for num in data[0].split():
	tmp, data = imap.fetch(num, '(RFC822)')
	print('Message: {0}\n'.format(num))
	pprint.pprint(data[0][1])
	break
imap.close()

In this program, we are using IMAP4_SSL to establish a connection to the host. Inside the for loop, we are retrieving all the messages from the inbox and printing them in a proper format with indentations using Python prettyprint(pprint). After the loop breaks, we make sure the connection to the server is closed by imap.close()

How to Read Emails and Download their attachements?

To read+download the received attachments, we will need to download the following modules:

  • imaplib – provides a standard email protocol in order to access the messages
  • base64 – Allows encoding/decoding of binary data to ASCII
  • os – Used to manage directories in the local system
  • email – Reads, writes, and sends emails
import imaplib
import base64
import os
import email

address = "[email protected]"
password = "samplepassword"

# For this example, our host will be gmail
mailbox = imaplib.IMAP_SSL("imap.gmail.com", 993)
mailbox.login(address, password)
mailbox.select('Inbox')

type, data = mail.search(None, 'ALL')
mail_ids = data[0]
id_list = mail_ids.split()

for num in data[0].split():
    typ, data = mail.fetch(num, '(RFC822)' )
    raw_email = data[0][1]

# Converting bytes into string format
    raw_email_string = raw_email.decode('utf-8')
    email_message = email.message_from_string(raw_email_string)

# Iteration to downlaod the attachments
    for part in email_message.walk():
        if part.get_content_maintype() == 'multipart':
            continue
        if part.get('Content-Disposition') is None:
            continue
        fileName = part.get_filename()
        if bool(fileName):
            filePath = os.path.join('/Users/sanketdoshi/python/', fileName)
            if not os.path.isfile(filePath) :
                fp = open(filePath, 'wb')
                fp.write(part.get_payload(decode=True))
                fp.close()

# Closing the session and logging out
mailbox.close()
mailbox.logout()

How Retrieve Recently sent Google Email details using Python IMAP?

The next program will explain to you how we can produce recently sent Google email details via Python. The modules which we will require are:

Your Gmail account should have IMAP enabled before you continue. To enable, look at the following steps.

Go to,

  • Settings,
  • Forwarding and POP/IMAP
  • IMAP access
  • Enable IMAP
Enable-gmail-imap

You may continue with the program after the above steps have been ensured.

# import the modules
import imaplib							
import email
from email.header import decode_header
import webbrowser
import os

# Initiate a connection with the host (in this case, Gmail)
server ="imap.gmail.com"					
imap = imaplib.IMAP4_SSL(server)

# Create variables containing Email address and password
address ="[email protected]"
password ="********"

# login into the gmail account
imap.login(address, password)			

# Using SELECT to chose the e-mails.
res, messages = imap.select('"[Gmail]/Sent Mail"')

# Caluclating the total number of sent Emails
messages = int(messages[0])

# Number of recent e-mails to be fetched
n = 3

# Iterating over the sent emails
for i in range(messages, messages - n, -1):
	res, msg = imap.fetch(str(i), "(RFC822)") # Using the RFC822 protocol	
	for response in msg:
		if isinstance(response, tuple):
			msg = email.message_from_bytes(response[1])
			
			# Retrieving the senders email 
			From = msg["From"]

			# Retrieving the subject of the email
			subject = msg["Subject"]

			# Printing out Subject and sender details
			print("From : ", From)
			print("Subject : ", subject)

Sample Output

NOTE: This is just a sample output to represent how YOUR output should look like.

From : Bob Smith  <[email protected]>   
Subject : Welcome to PythonPool.com

From : John Jacob <[email protected]>   
Subject : Python Tutorials Explained Easy

From : Bill Nye <[email protected]>  
Subject : Check Out our Website !

How to Delete Emails from your Inbox using Python imaplib?

The below implementation demonstrates how you can delete multiple emails from your inbox.

import imaplib
# Connecting to Host Gmail on port 993
sampleSession = imaplib.IMAP4_SSL('imap.gmail.com', 993)

#Logging into the account that we want to delete emails from
sampleSession.login("[email protected]","password")

# Selecting Inbox
sampleSession.select('Inbox')

# Looking for all Emails
typ, data = sampleSession.search(None, 'ALL')

for num in data[0].split():
   sampleSession.store(num, '+FLAGS', '\\Deleted')

# Permanently removing deleted items from the selected mailbox.
sampleSession.expunge()

# Closes the current mailbox we're working with
sampleSession.close()

# Stopping the connection to the host
sampleSession.logout()

Creating Folders using imaplib

When implementing nested mailboxes, the mailboxes at the top of the session are marked \\Noselect. We can remove these flags by explicitly creating folders on each level.

folder = "C:/Admin/Desktop/sampleFolder"

target = " "

for level in folder.split('/'):
    target += "{}/".format(level)
    imap.create(target)

imap() Function from Python multiprocessing

In the Python module, multiprocessing there is a class called pool. Within the class, there is a function called imap(). But before you know what imap() does, you must know what map() is. pool.map() takes the function that we want to be parallelized and iterable as the arguments. It runs the given function on every item of the iterable. It also takes an optional chunksize argument, which splits the iterable into the chunks equal to the given size and passes each chunk as a separate task. The pool.imap() is almost the same as the pool.map() method. The difference is that the result of each item is received as soon as it is ready, instead of waiting for all of them to be finished. Moreover, the map() method converts the iterable into a list. However, the imap() method does not have that feature.

How to Handle Errors in imaplib?

The most straightforward solution to handle errors in imaplib is to use try and except block. You can write something like:

try:
    mail.login(username, password)
    print "Logged in as %r !" % username
except imaplib.IMAP4.error:
    print "Log in failed.

This is just an example. Your actual implementations may vary from code to code.

imaplib vs IMAPClient

imaplibIMAPClient
imaplib implements a client for communicating with IMAP version 4 servers. IMAPClient is an easy-to-use, Pythonic, and complete IMAP client library. Furthermore, it uses the imaplib module itself but under a different API.
Error checking of return values from imaplib functions may be required.Error checking of return values from the IMAPClient module is not required.
Parsing processes of return values are done by the caller function.Return values are fully and readily parsed on arrival.

FAQs on Python IMAP

What’s the difference between POP and IMAP?

POP3 downloads the email from a server to a single computer then deletes the email from the server. On the other hand, IMAP has the ability to store the message on a server and synchronize the message across multiple devices.

Conclusion

imaplib is one of the essential modules when it comes to marketing and modern e-commerce businesses. Therefore, we have looked at various applications of the module and its functions. The differences between imaplib and the newer IMAPclient have been established.

Subscribe
Notify of
guest
0 Comments
Inline Feedbacks
View all comments