Write a Python Program to Merge Mails

Merging emails can be a useful task when you have multiple email accounts and want to keep track of all your emails in one place.

In this tutorial, we will show you how to merge emails using Python.


First, we need to import the necessary libraries.

We will be using the imaplib and email libraries to access and parse the emails, respectively.

import imaplib
import email

Next, we need to define our email accounts and credentials.

In this example, we will be using two Gmail accounts.

account_1 = {
    "username": "[email protected]",
    "password": "password1"
}

account_2 = {
    "username": "[email protected]",
    "password": "password2"
}

Next, we need to connect to the email servers using the imaplib library.

# Connect to account 1
mail_1 = imaplib.IMAP4_SSL('imap.gmail.com')
mail_1.login(account_1['username'], account_1['password'])

# Connect to account 2
mail_2 = imaplib.IMAP4_SSL('imap.gmail.com')
mail_2.login(account_2['username'], account_2['password'])

After connecting to the email servers, we need to select the mailbox to work with.

In this example, we will be using the Inbox mailbox.

# Select the mailbox to work with
mail_1.select('Inbox')
mail_2.select('Inbox')

Next, we need to search for emails in both accounts.

In this example, we will be searching for all emails that were received in the last 24 hours.

# Search for emails in account 1
result, data = mail_1.search(None, "SINCE", "24 hours ago")

# Search for emails in account 2
result, data = mail_2.search(None, "SINCE", "24 hours ago")

After searching for the emails, we need to loop through each email and append it to a list.

# Loop through each email in account 1 and append it to a list
mails = []
for num in data[0].split():
    _, data = mail_1.fetch(num, "(RFC822)")
    msg = email.message_from_bytes(data[0][1])
    mails.append(msg)

# Loop through each email in account 2 and append it to the same list
for num in data[0].split():
    _, data = mail_2.fetch(num, "(RFC822)")
    msg = email.message_from_bytes(data[0][1])
    mails.append(msg)

Finally, we can sort the list of emails by date and print them out.

# Sort the list of emails by date
mails.sort(key=lambda x: x['date'], reverse=True)

# Print out the merged emails
for mail in mails:
    print(mail['from'], mail['subject'], mail['date'])

That’s it!

Now you know how to merge emails using Python.