Automate Your Gmail Workflow — A Python Script to Manage Multiple Inboxes

Have multiple Gmail accounts and tired of manually checking each one for new emails? Managing several inboxes can be time-consuming, but there’s a way to automate the process and streamline your day. With Python, you can set up a script that checks all your Gmail accounts for new emails and gives you a quick summary of what’s waiting in each mailbox.

Prerequisites

Before running the script, ensure you have the following:

  1. Python installed on your system.
  2. IMAP access enabled in each of your Gmail accounts.
  3. The imaplib and email modules (which are part of the standard Python library).

To enable IMAP access for your Gmail accounts, follow these steps:

  1. Sign in to Your Gmail Account: Open your web browser and navigate to Gmail. Sign in using your Gmail credentials.

2. Access Gmail Settings:

  • In the top-right corner of the Gmail interface, click on the gear icon (⚙️).
  • From the dropdown menu, select See all settings.

3. Enable IMAP:

  • In the settings window, go to the Forwarding and POP/IMAP tab.
  • Scroll down to the IMAP access section.
  • Click the option to Enable IMAP.
  • Finally, click Save Changes at the bottom of the page.

4. (Optional) Generate an App Password:

  • If you have two-factor authentication (2FA) enabled, you’ll need to generate an app password.
  • Go to your Google Account Security page.
  • Under the “Signing in to Google” section, select App passwords.
  • Follow the prompts to create a new app password for use with the script.

These steps ensure that your Gmail accounts are accessible through IMAP, allowing the Python script below to check for new emails in each mailbox and lists new emails (From and Subject).

The Python Script: check_gmail.py

Now that you’ve enabled IMAP access in each of your Gmail accounts, you can create a Python script that checks each mailbox for new emails. This script will loop through all four accounts and list any new emails, displaying the sender and the subject line.

Here’s how you can set up the script:

1. Create a Script File

Start by creating a new Python script file named check_gmail.py. You can place this file in any directory on your system where you want to run the script.

touch check_gmail.py

2. Write the Script

Open the check_gmail.py file in your preferred text editor and add the following code. This script uses the imaplib and email libraries to connect to Gmail, check for new emails, and display the sender and subject of each unread email.

import imaplib
import email
from email.header import decode_header

# List of Gmail accounts with their respective credentials
gmail_accounts = [
    {"email": "your_email_1@gmail.com", "password": "your_password_1"},
    {"email": "your_email_2@gmail.com", "password": "your_password_2"},
    {"email": "your_email_3@gmail.com", "password": "your_password_3"},
    {"email": "your_email_4@gmail.com", "password": "your_password_4"}
]

def check_emails(email_user, email_pass):
    # Connect to Gmail's IMAP server
    mail = imaplib.IMAP4_SSL("imap.gmail.com")
    
    # Login to the account
    mail.login(email_user, email_pass)
    
    # Select the mailbox you want to check (inbox)
    mail.select("inbox")
    
    # Search for all unseen emails
    status, messages = mail.search(None, "UNSEEN")
    
    # Get the list of email IDs
    email_ids = messages[0].split()
    
    # Loop through each email ID to fetch the email data
    for e_id in email_ids:
        status, msg_data = mail.fetch(e_id, "(RFC822)")
        msg = email.message_from_bytes(msg_data[0][1])
        
        # Decode the email subject
        subject, encoding = decode_header(msg["Subject"])[0]
        if isinstance(subject, bytes):
            subject = subject.decode(encoding if encoding else "utf-8")
        
        # Get the email sender
        from_ = msg.get("From")
        
        # Print the sender and subject
        print(f"From: {from_}\nSubject: {subject}\n")
    
    # Logout from the account
    mail.logout()

# Loop through each Gmail account and check for new emails
for account in gmail_accounts:
    print(f"Checking emails for: {account['email']}")
    check_emails(account["email"], account["password"])
    print("-" * 50)

3. How the Script Works

  • Gmail Accounts List: The script starts by defining a list of dictionaries, each containing the email and password of one of your Gmail accounts.
  • IMAP Connection: For each account, the script connects to Gmail’s IMAP server using the imaplib.IMAP4_SSL method.
  • Login and Select Mailbox: The script logs into the account and selects the “inbox” folder to check for new emails.
  • Search and Fetch Emails: It searches for all unseen (unread) emails using the mail.search(None, "UNSEEN") method. For each unread email, it fetches the full email data.
  • Decode Subject and Print Results: The subject of the email is decoded to handle any encoded text. The script then prints the sender and subject for each unread email.
  • Loop Through Accounts: Finally, the script loops through all the provided Gmail accounts, checking each one and printing the results.

4. Running the Script

To run the script, open your terminal, navigate to the directory containing check_gmail.py, and execute it:

python check_gmail.py

This script will output a list of new emails for each Gmail account, showing the sender and the subject of each message. It’s a handy tool to keep track of new emails across multiple Gmail accounts in one go.

If you’re using two-factor authentication (2FA) with any of these accounts, remember to replace the password with an app-specific password generated for this script. This ensures secure and uninterrupted access.


Thank you for following along with this tutorial. We hope you found it helpful and informative. If you have any questions, or if you would like to suggest new Python code examples or topics for future tutorials/articles, please feel free to join and comment. Your feedback and suggestions are always welcome!

You can find the same tutorial on Medium.com.

Leave a Reply