◈ Mail → Excel

IMAP to Excel: one method for any mailbox

By the Mail → Excel team · Updated 2026-10-18

IMAP is the lowest common denominator: if a provider supports mail clients, it supports export. Here is the full working path.

Step 1 — get an app password

Never use your main password. Providers require an application-specific password or OAuth token:

Step 2 — connect and filter

import imaplib, email, ssl

imap = imaplib.IMAP4_SSL("imap.example.com", 993, ssl_context=ssl.create_default_context())
imap.login("user@example.com", "APP_PASSWORD")
imap.select("INBOX", readonly=True)

# только письма за период, без удаления и отметок «прочитано»
status, data = imap.search(None, '(SINCE 01-Sep-2026)')
ids = data[0].split()
readonly=True is important: it guarantees the script will not mark messages as read or delete anything.

Step 3 — decode and map fields

Headers are encoded (RFC 2047), so decode them before writing to Excel:

from email.header import decode_header, make_header

def text(value):
    return str(make_header(decode_header(value or ""))).strip()

for num in ids:
    status, msg_data = imap.fetch(num, "(RFC822)")
    msg = email.message_from_bytes(msg_data[0][1])
    row = {
        "date": text(msg["Date"]),
        "from": text(msg["From"]),
        "subject": text(msg["Subject"]),
        "attachments": ", ".join(
            p.get_filename() for p in msg.walk() if p.get_filename()
        ),
    }

Step 4 — write Excel

from openpyxl import Workbook
wb = Workbook(); ws = wb.active
ws.append(["Date", "From", "Subject", "Attachments"])
for row in rows:
    ws.append([row["date"], row["from"], row["subject"], row["attachments"]])
wb.save("mail.xlsx")

Common problems

SymptomCause
LOGIN failedNormal password instead of app password, or IMAP disabled
Mojibake in subjectsMissing RFC 2047 decoding
Attachments missingMultipart message — iterate msg.walk()
Script hangsNo timeout on the IMAP connection; large folder without date filter

If you want the finished script with filters, Excel output and an attachments column — it is $3 in USDT here.

FAQ

Is IMAP export allowed by providers?

Yes, IMAP is a standard protocol intended for mail clients. Read-only access does not violate typical terms. Do not use it to mass-download other people’s mailboxes.

Will the script mark my emails as read?

Not if the folder is opened read-only (readonly=True). That is the recommended default.

Can I export only one folder?

Yes — change the folder name in imap.select(). Use quoted names for folders with spaces.

What about attachments?

Iterate msg.walk(), find parts with a filename and save the decoded payload. Handle duplicate filenames.

Related guides