Skip to main content

IMAP Thingy

An IMAP scripting library, primarily to make email filters.

Ever complained about receiving the same emails on multiple inboxes? Or wanted to auto-archive receipts that you've already opened? Or wanted your emails to get sorted automatically in some other way?

Well, complain no more! (or at least not for this reason)

IMAP Thingy is a library that lets its users create advanced IMAP filters. Possibly on multiple emails, possibly even on multiple accounts.

Installation

pip install imap-thingy

or, for the unreleased state of main:

pip install git+https://github.com/sgorblex/imap-thingy.git

Usage and examples

Here is a simple example which loads credentials from an accounts.json file that looks something like this:

[
  {
    "name": "beautiful gmail account",
    "type": "gmail",
    "username": "myaddress@gmail.com",
    "password": "ana ppp asw ord"
  },
  {
    "name": "beautiful custom account",
    "host": "mydomain.com",
    "port": 993,
    "username": "its.a.me@mydomain.com",
    "password": "my_super_secret_pw"
  }
]

At the moment we do not support OAUTH (PRs welcome :), so if you're using something like GMail you will have to generate an app-password.

As for the main script, which simply applies some filters (probably the most useful):

# my_beautiful_script.py

from imap_thingy.accounts import Path, accounts_from_json
from imap_thingy.filters import Filter, If, FromIs, SubjectMatches, ToIs, MoveTo, MarkAsRead

from dmarc import dmarc_pairs

import argparse

def main():
    parser = argparse.ArgumentParser(description="imap_filters: my personal IMAP filters")
    parser.add_argument("--dry-run", action="store_true", help="Print actions instead of executing them")
    args = parser.parse_args()

    accounts = accounts_from_json("accounts.json")
    gmail = accounts["beautiful gmail account"]
    custom = accounts["beautiful custom account"]

    pairs = [
        # In account "beautiful gmail account", move all mail directed to "members@boringassociation.org" to "Boring Association" folder (marking as read first)
        (gmail / "INBOX", Filter(ToIs("members@boringassociation.org"), MarkAsRead() + MoveTo(Path("Boring Association")))),
        # In account "beautiful custom account", move all mail from "googledev-noreply@google.com" to "Dev Stuff.Google Developer Program" folder. Note that folder delimiter may differ between servers
        (custom / "INBOX", Filter(FromIs("googledev-noreply@google.com"), MarkAsRead() + MoveTo(Path("Dev Stuff.Google Developer Program")))),
        # A filter based on a complex criterion and a series of actions
        (gmail / "INBOX", If(FromIs("list4nerds@nerduniversity.edu") & SubjectMatches(r"List Digest, Vol \d+")).then(MarkAsRead() + MoveTo(Path("List For Nerds")))),
    ]
    pairs.extend(dmarc_pairs(custom, "dmarcreport@microsoft.com", "Postmaster.DMARC Reports"))

    for folder, f in pairs:
        folder.run(f, dry_run=args.dry_run)


if __name__ == "__main__":
    main()

The important parts are accounts_from_json, pairs (folder + filter), and looping over pairs and calling folder.run(f, ...). Folders are obtained from an account (e.g. account / "INBOX", account.inbox). For type hints or direct use, import Folder from imap_thingy.accounts. Criteria that can be expressed purely in IMAP (e.g. FromIs, SubjectContains, BodyContains) use server-side search only; criteria that need body parsing (e.g. SubjectMatches with regex, or BodyMatches which searches decoded plain/HTML body text with re.search) use a per-run fetch cache to minimize redundant fetches within a run(), but messages that have had actions applied may be evicted from the cache and fetched again if they are re-selected later in the same run().

Note: The library no longer configures logging automatically. The previously documented imap_thingy.logging.setup_logging() helper is kept only as a deprecated compatibility shim and should not be used in new code. Instead, configure logging explicitly in your application near the entry point (for example with logging.basicConfig(level=logging.INFO, format="%(levelname)s %(name)s %(message)s")) so that loggers under imap_thingy emit to your handlers.

Arbitrarily complex filters can be implemented in Python, likely via imapclient and/or mailparser, if not directly via our bindings. For example, here is a custom helper that returns (folder, filter) pairs to automatically move DMARC reports, while first trashing the previews:

# dmarc.py

from imap_thingy.accounts import Account, Path
from imap_thingy.filters import If, FromIs, SubjectMatches, MoveTo, Trash

def dmarc_pairs(account: Account, sender: str, folder: str, delete_preview: bool = True, base_folder: str = "INBOX"):
    f = account / base_folder
    pairs = []
    if delete_preview:
        pairs.append((f, If(FromIs(sender) & SubjectMatches("[Preview] .*")).then(Trash())))
    pairs.append((f, If(FromIs(sender)).then(MoveTo(Path(folder)))))
    return pairs

Development

Tooling is pinned with mise; run everything through mise run <task>:

Task What it does
setup Install Python dependencies into .venv
fix Ruff auto-fix and format, then mypy
check Ruff lint and format check, then mypy
test Run the test suite; extra args go to pytest (mise run test -- tests/test_criteria.py)
build Build sdist and wheel
clean / clean-all Remove caches and build outputs (clean-all also removes .venv)

Releases and CHANGELOG.md are automated by Release Please from Conventional Commit squash titles; dependency updates come from Renovate.

Contributing

Feel free to raise issues or open pull requests! Branch, commit and PR conventions are in AGENTS.md.

License

GPL v.3 or later

Metadata

Release files for imap-thingy 0.4.0

For a detailed explanation of source distributions (sdists) and built distributions (wheels), please see the package formats documentation.

Source distribution (sdist)

Source distribution for imap-thingy 0.4.0
File Size Uploaded
imap_thingy-0.4.0.tar.gz 42.9 kB Details

Built distribution (wheel)

Table of built distributions (wheels) for imap-thingy 0.4.0
File Interpreter ABI Platform
imap_thingy-0.4.0-py3-none-any.whl Python 3 none any Details

Total release size: 84.2 kB

Release files / imap_thingy-0.4.0.tar.gz

Download URL imap_thingy-0.4.0.tar.gz
Size 42.9 kB
Tags Source
SHA-256 checksum
How to use checksums
bb13d23ccea50d1ac0320fdd3fd7c96ee7cf8ed3d0a381621b5eca42fb37fc05
BLAKE2b-256 checksum
How to use checksums
e3fc7c7af1260e6b15ad10d4b27b87731a5b2e2cff4682684d60e6afa9c0514a
Upload date
Uploaded using Trusted Publishing?
What is trusted publishing?
Yes
Uploaded via twine/7.0.0 CPython/3.13.14

Provenance

Provenance describes where a file came from. On PyPI, provenance is shared via attestations, which provide a verifiable record of the build or publishing details. View details, limitations and caveats.

PyPI Publish Attestation

PyPI verified that this artifact, at this checksum, originated from the publisher listed below.

Signed by GitHub Actions, verified by PyPI on Oct 13, 2026.

Transparency log

Release files / imap_thingy-0.4.0-py3-none-any.whl

Download URL imap_thingy-0.4.0-py3-none-any.whl
Size 41.2 kB
Tags Python 3
SHA-256 checksum
How to use checksums
26c98fa29b8f9512575bc441a5d249e16ad6916e4791f1143639ba3d4421ef6d
BLAKE2b-256 checksum
How to use checksums
0f0f01c920c4833c423b5e7e102ee1850665eda9280ed001dbb90f3e648a77cc
Upload date
Uploaded using Trusted Publishing?
What is trusted publishing?
Yes
Uploaded via twine/7.0.0 CPython/3.13.14

Provenance

Provenance describes where a file came from. On PyPI, provenance is shared via attestations, which provide a verifiable record of the build or publishing details. View details, limitations and caveats.

PyPI Publish Attestation

PyPI verified that this artifact, at this checksum, originated from the publisher listed below.

Signed by GitHub Actions, verified by PyPI on Oct 13, 2026.

Transparency log

Release history Release notifications | RSS feed

0.6.0

2 release files

0.5.0

2 release files

This release

0.4.0 This release

2 release files

Anthropic, PBC Visionary sponsor Bloomberg Visionary sponsor Hudson River Trading Visionary sponsor Meta Visionary sponsor NVIDIA Visionary sponsor Microsoft Sustainability sponsor Depot Continuous Integration AWS Cloud computing and Security Sponsor Datadog Monitoring Fastly CDN Google Download Analytics Sentry Error logging StatusPage Status page