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.
We will look at imaplib
, which is Python’s client-side library used to access emails over the IMAP protocol.
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
import imaplibuser = 'yourmail@gmail.com'password = 'password'host = 'imap.gmail.com'# Connect securely with SSLimap = imaplib.IMAP4_SSL(host)## Login to remote serverimap.login(user, password)imap.select('Inbox')tmp, messages = imap.search(None, 'ALL')for num in messages[0].split():# Retrieve email message by IDtmp, data = imap.fetch(num, '(RFC822)')print('Message: {0}\n'.format(data[0][1]))breakimap.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.
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.