Trusted answers to developer questions
Trusted Answers to Developer Questions

Related Tags

python
imap
library
communitycreator

How to use the IMAP protocol in Python

Chibuike Nwachukwu

Internet Mail Access Protocol (IMAP) is an internet standard protocol used by email clients to retrieve email messages from a mail server.

To do this, it reads the email on the mail server without downloading it on the local computer.

IMAP is used to retrieve emails from the server

We will look at imaplib, which is Python’s client-side library used to access emails over the IMAP protocol.

How to use imaplib

imaplib allows us to make use of the IMAP protocol right in Python. It makes available methods we can interact with within our code, to read from remote IMAP servers and perform other activities on the server.

To import it into our Python project, we simply include at the top of our file, as seen below.

import imaplib

Code

import imaplib

user = 'yourmail@gmail.com'
password = 'password'
host = 'imap.gmail.com'

# Connect securely with SSL
imap = imaplib.IMAP4_SSL(host)

## Login to remote server
imap.login(user, password)

imap.select('Inbox')

tmp, messages = imap.search(None, 'ALL')
for num in messages[0].split():
	# Retrieve email message by ID
	tmp, data = imap.fetch(num, '(RFC822)')
	print('Message: {0}\n'.format(data[0][1]))
	break
	
imap.close()
imap.logout()

You need to replace the user and password variables with your Gmail username and password to run this code. You might need to change your Google account security settings to enable access for less secure apps for this to work. Click here to turn on access to less secure apps.

Explanation

In the code above, we connect with the remote server and authenticate to this server with email and password credentials.

Since IMAP works with mailboxes, we need to specify the mailbox we wish to access. In our case, we choose the Inbox mailbox. There are other mailboxes, like sent, spam, etc., available in Gmail.

Then, we call IMAP search method to retrieve all the messages, which we would go on to loop through. Next, we use the imap.fetch() method, which makes use of the standard format specified in RFC 822 to fetch the actual email message by ID. We then display the message by calling the print function.

Lastly, we close the connection and logout.

RELATED TAGS

python
imap
library
communitycreator
RELATED COURSES

View all Courses

Keep Exploring