Skip to content

Instantly share code, notes, and snippets.

@chronikum
Created May 31, 2024 12:08
Show Gist options
  • Save chronikum/29abe71431bf8244d491d71e45287f9a to your computer and use it in GitHub Desktop.
Save chronikum/29abe71431bf8244d491d71e45287f9a to your computer and use it in GitHub Desktop.
This script will help you to export all email in your mailbox locally in a folder. (Imap)
# install imaplib2 before running.
# written for python3
# adjust your IMAP server details!
import imaplib
import email
from email.policy import default
import os
# IMAP server details
IMAP_SERVER = 'your_imap_server'
EMAIL_ACCOUNT = 'your_email_address'
PASSWORD = 'your_email_password'
OUTPUT_DIR = 'emails_backup'
# Create output directory if it doesn't exist
if not os.path.exists(OUTPUT_DIR):
os.makedirs(OUTPUT_DIR)
def save_email(mailbox, email_id, msg_data):
for response_part in msg_data:
if isinstance(response_part, tuple):
msg = email.message_from_bytes(response_part[1], policy=default)
# Get email subject
subject = msg['subject'] if msg['subject'] else 'No_Subject'
subject = "".join([c if c.isalnum() else "_" for c in subject])
# Save email to a file
mailbox_dir = os.path.join(OUTPUT_DIR, mailbox.replace('/', '_'))
if not os.path.exists(mailbox_dir):
os.makedirs(mailbox_dir)
with open(os.path.join(mailbox_dir, f'{email_id.decode()}_{subject}.eml'), 'wb') as f:
f.write(response_part[1])
# Connect to the server and login
mail = imaplib.IMAP4_SSL(IMAP_SERVER)
mail.login(EMAIL_ACCOUNT, PASSWORD)
# Get all mailboxes
status, mailboxes = mail.list()
if status != 'OK':
print("Failed to retrieve mailboxes")
mail.logout()
exit()
for mailbox in mailboxes:
mailbox_name = mailbox.decode().split(' "/" ')[1].strip('"')
print(f"Processing mailbox: {mailbox_name}")
# Select the mailbox
status, data = mail.select(mailbox_name)
if status != 'OK':
print(f"Failed to select mailbox: {mailbox_name}")
continue
# Search for all emails in the selected mailbox
status, email_ids = mail.search(None, 'ALL')
if status != 'OK':
print(f"Failed to retrieve emails from mailbox: {mailbox_name}")
continue
# Convert email ids to a list
email_ids = email_ids[0].split()
for email_id in email_ids:
status, msg_data = mail.fetch(email_id, '(RFC822)')
save_email(mailbox_name, email_id, msg_data)
# Logout and close connection
mail.logout()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment