Python Network Programming IMAP
Python Network Programming with IMAP
IMAP is an email retrieval protocol that doesn’t download emails. It simply reads and displays them. This is very useful in low-bandwidth environments. Python’s client library, called imaplib, is used to access emails via the IMAP protocol.
IMAP stands for Internet Message Access Protocol, which was first proposed in 1986.
Key Points .
- IMAP allows client programs to manipulate emails on a server without having to download them to the local computer.
-
Emails are stored and maintained by a remote server.
-
It allows us to take actions, such as downloading or deleting emails, without having to read them. It allows us to create, manipulate, and delete remote information folders, called mailboxes.
-
IMAP enables users to search for email.
-
It allows simultaneous access to multiple mailboxes on multiple mail servers.
IMAP Commands
The following table describes some of the IMAP commands.
S.N. | Command Description |
---|---|
1 | IMAP_LOGIN This command opens a connection. |
2 | CAPABILITY This command lists the capabilities supported by the server. |
3 | NOOP This command is used to periodically poll for new mail or mail status updates during a period of inactivity. |
4 | SELECT This command helps select a mailbox to access mail from. |
5 | EXAMINE This command is the same as the SELECT command, except that it does not allow changes to the mailbox. |
6 | CREATE This command is used to create a mailbox with a specified name. |
7 | DELETE This command is used to permanently delete a mailbox with a specified name. |
8 | RENAME is used to change the name of a mailbox. |
9 | LOGOUT This command notifies the server that the client has completed the session. The server must send a BYE unsigned response before responding with an OK and then close the network connection. |
Example
In the following example, we log in to a Gmail server using user credentials. We then select and display the emails in the inbox. A for loop is used to display the retrieved emails one by one, and finally close the connection.
import imaplib
import print
imap_host = 'imap.gmail.com'
imap_user = 'username@gmail.com'
imap_pass = 'password'
# connect to host using SSL
imap = imaplib.IMAP4_SSL(imap_host)
## login to server
imap.login(imap_user, imap_pass)
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()
Depending on the mailbox configuration, the email will be displayed.