Receiving email using the imaplib library

IMAP stands for Internet Message Access Protocol. It's used to access emails on a remote server through your local machine. IMAP allows simultaneous access by multiple clients to your email. IMAP is more suitable when you access your email via different locations.

The IMAP protocol works on two ports:

  • Port 143: The default non-encrypted port
  • Port 993: The encrypted port

Now, we're going to see an example using the imaplib library. Create a script, imap_email.py, and write the following content in it:

import imaplib
import pprint
import getpass

imap_server = 'imap.gmail.com'
username = 'Emaild_address'
password = getpass.getpass()

imap_obj = imaplib.IMAP4_SSL(imap_server)
imap_obj.login(username, password)
imap_obj.select('Inbox')
temp, data_obj = imap_obj.search(None, 'ALL')
for data in data_obj[0].split():
temp, data_obj = imap_obj.fetch(data, '(RFC822)')
print('Message: {0} '.format(data))
pprint.pprint(data_obj[0][1])
break

imap_obj.close()

Run the script, as follows:

student@ubuntu:~$ python3 imap_email.py

As output, you'll get all of the emails from the specified folder.

In the preceding example, first, we're importing the imaplib library, which is used in Python to receive an email securely via the IMAP protocol. Then, we state the specific email server and our user credentials—that is, our username and password. After that, we provide that username and password to the IMAP SSL server. We're using the 'select('Inbox')' function over imap_obj to display messages in the inbox. Then we use a for loop to display messages that have been fetched one by one. To display messages, we use "pretty print"—that is, the pprint.pprint() function-because it formats your object, writes it into the data stream, and passes it as an argument. Then, finally, the connection is closed.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset