# Python Imaplib Module

The `imaplib` module defines three classes, `IMAP4`, `IMAP4_SSL` and `IMAP4_stream`, which encapsulate a connection to an IMAP4 server and implement the IMAP4rev1 client protocol as defined in RFC 2060. It is used to access emails on a mail server.

## Importing the Module

```python
import imaplib
```

## Connecting to a Server

To connect to an IMAP server securely, use `IMAP4_SSL`.

```python
import imaplib

# Connect to the server (default port 993 for SSL)
mail = imaplib.IMAP4_SSL('imap.gmail.com')
```

## Authentication

```python
mail.login('your_email@gmail.com', 'your_password')
```

## Selecting a Mailbox

Before searching or fetching, you must select a mailbox (folder).

```python
# Select the inbox
status, messages = mail.select('INBOX')
print(f"Status: {status}, Total Messages: {messages[0].decode('utf-8')}")
```

## Searching for Emails

You can search for emails using criteria like 'ALL', 'UNSEEN', 'FROM', etc.

```python
# Search for all emails
typ, data = mail.search(None, 'ALL')

# Get the list of email IDs
mail_ids = data[0].split()
print(f"Found {len(mail_ids)} emails")
```

## Fetching Emails

To retrieve the content of an email, use the `fetch()` method.

```python
if mail_ids:
    # Fetch the latest email (last ID in the list)
    latest_email_id = mail_ids[-1]
    
    # Fetch the email body (RFC822)
    typ, data = mail.fetch(latest_email_id, '(RFC822)')
    
    # The data is a list of tuples. The email content is in the second element of the tuple.
    for response_part in data:
        if isinstance(response_part, tuple):
            print(response_part[1].decode('utf-8'))
```

## Closing the Connection

```python
mail.close()
mail.logout()
```

[[programming/python/python]]