Fundamentals

Python Script to Automate Email Sorting

Python Script to Automate Email Sorting

Manual inbox triage drains hours from creators, marketers, and founders. This guide delivers a copy-paste executable Python script to automate email sorting using IMAP and keyword-based routing. Run it locally or schedule it to maintain a zero-clutter inbox automatically.

Prerequisites & Secure Connection Setup

Before executing the script, ensure your environment is configured correctly by reviewing core Python AI Fundamentals for Non-Developers concepts, particularly around secure credential handling and package management. Enable IMAP access in your email provider settings (e.g., Gmail > Settings > Forwarding and POP/IMAP). Generate a dedicated 16-character App Password instead of using your primary account password.

pip install imaplib email

The Complete Email Sorting Script

The following procedural script connects securely, scans unread messages, and routes them into predefined folders based on subject line keywords. Replace the placeholder credentials and adjust SORT_RULES to match your workflow.

import imaplib
import email
from email.header import decode_header
import os

# Configuration
IMAP_SERVER = 'imap.gmail.com'
EMAIL_ADDRESS = 'your_email@gmail.com'
APP_PASSWORD = 'your_16_char_app_password'

# Sorting Rules
SORT_RULES = {
 'Invoices': ['invoice', 'receipt', 'payment'],
 'Newsletters': ['newsletter', 'update', 'digest'],
 'Clients': ['project', 'contract', 'meeting']
}

def connect_and_sort():
 mail = imaplib.IMAP4_SSL(IMAP_SERVER)
 mail.login(EMAIL_ADDRESS, APP_PASSWORD)
 mail.select('inbox')
 
 # Fetch recent unread emails
 status, messages = mail.search(None, 'UNSEEN')
 email_ids = messages[0].split()
 
 for eid in email_ids:
 status, msg_data = mail.fetch(eid, '(RFC822)')
 raw_email = msg_data[0][1]
 msg = email.message_from_bytes(raw_email)
 subject = decode_header(msg['Subject'])[0][0]
 if isinstance(subject, bytes):
 subject = subject.decode('utf-8', errors='ignore')
 
 for folder, keywords in SORT_RULES.items():
 if any(kw.lower() in subject.lower() for kw in keywords):
 mail.copy(eid, folder)
 mail.store(eid, '+FLAGS', '\\Seen')
 break
 mail.logout()

if __name__ == '__main__':
 connect_and_sort()

Execution & Automated Scheduling

Run python email_sorter.py in your terminal to verify target folder creation and routing accuracy. Once tested manually, integrate the script into your daily workflow using cron or Task Scheduler. This approach aligns with proven strategies for Automating Repetitive Tasks, ensuring consistent inbox hygiene without manual intervention.

# macOS/Linux (cron)
0 */4 * * * /usr/bin/python3 /path/to/email_sorter.py >> /var/log/email_sorter.log 2>&1

# Windows (Task Scheduler)
# Action: Start a program
# Program: python.exe
# Arguments: C:\path\to\email_sorter.py

Troubleshooting Common IMAP & Auth Errors

Resolve frequent connection failures with these targeted patches.

# Fix 1: App Password Required (OAuth2 deprecated for basic IMAP)
# Generate at: Google Account > Security > App Passwords

# Fix 2: SSL Context for Strict Environments
import ssl
ctx = ssl.create_default_context()
mail = imaplib.IMAP4_SSL(IMAP_SERVER, ssl_context=ctx)

# Fix 3: Auto-create missing folders
mail.create('Invoices')