A snippet to download emails from an IMAP server based on a list of failed migrations on
Google Workspace. These will be saved according to the IMAP folder structure, in a
folder named emails
.
The entries.txt should be formatted as such:
email@example.com Email <029776C1-7F7D-495B-8643-7B6743D6EAA0@example.com> Sent Items
import imaplib
import email
import os
# IMAP server settings
imap_server = "imap.example.com"
username = "email@example.com"
password = "Password!"
# Read entries from the file
with open("entries.txt", "r") as file:
entries = file.read().splitlines()
# Connect to the IMAP server
imap = imaplib.IMAP4_SSL(imap_server)
imap.login(username, password)
# Create the "emails" folder if it doesn't exist
if not os.path.exists("emails"):
os.makedirs("emails")
# Iterate over the entries
for entry in entries:
# Split the entry into its components
parts = entry.split("\t")
if len(parts) == 5:
email_address, _, message_id, folder, _ = parts
else:
email_address, _, message_id, folder = parts
# Select the appropriate folder
quoted_folder = f'"{folder}"'.replace("/", ".")
status, _ = imap.select(quoted_folder)
# Replace '/' with '_' in the folder name to avoid creating subfolders
folder = folder.replace("/", "_")
# Create the subfolder if it doesn't exist
subfolder = os.path.join("emails", folder)
if not os.path.exists(subfolder):
os.makedirs(subfolder)
# Search for the message with the specific message ID
_, message_numbers = imap.search(None, f'HEADER Message-ID "{message_id}"')
# Iterate over the message numbers
for num in message_numbers[0].split():
# Fetch the message
_, msg_data = imap.fetch(num, "(RFC822)")
# Parse the message
email_message = email.message_from_bytes(msg_data[0][1])
# Generate a unique filename for the EML file
filename = f"{message_id}.eml"
# Save the email as an EML file in the corresponding subfolder
file_path = os.path.join(subfolder, filename)
with open(file_path, "w") as eml_file:
eml_file.write(email_message.as_string())
print(f"Email exported as {file_path}")
# Logout from the IMAP server
imap.logout()