Blog
Guides

How to bulk unsubscribe from emails with Python

DK
Dan Kowalsky
Founder ·

Newsletters, product updates, "we miss you" offers: they pile up faster than anyone unsubscribes. Gmail and Outlook both have an Unsubscribe button, but it works one email at a time, and neither tells you which lists send the most or which ones you never open.

This guide builds a small tool that does both. It lists every mailing list that emailed you lately, busiest first, with how much of it you actually read. Then it unsubscribes from the ones you pick and clears out what they already sent. It works on Gmail or Outlook, and once it's deployed, everyone on your team can run it on their own inbox.

The complete code is in the Callables cookbook on GitHub: the providers/google/gmail/ and providers/microsoft/outlook/ folders. Pick your mail provider, and this whole page follows:

You'll use the Gmail API with the gmail.modify scope, which can read, label, archive and send mail.

How unsubscribing works under the hood

Legitimate mailing lists add a List-Unsubscribe header to every email (RFC 2369). It's invisible in your mail app, and it's what powers the Unsubscribe button. It offers one or both of:

List-Unsubscribe: <https://news.example.com/u/8f3a>, <mailto:[email protected]?subject=unsubscribe>
List-Unsubscribe-Post: List-Unsubscribe=One-Click

That gives three ways out, from best to worst:

MethodHow it worksDone automatically?
One-click (RFC 8058)A POST to the https link. Sent when List-Unsubscribe-Post is presentYes
EmailSend a message to the mailto: address, from your own accountYes
Link onlyA web page that may ask you to click a button or fill in a formNo: you get the link

Gmail and Yahoo now require one-click unsubscribe from bulk senders, so most big lists support the first.

The header also does something more useful: it identifies mailing lists. Personal email and receipts don't have it, so filtering on it finds exactly the subscriptions.

1. Set up the OAuth app

The tool works on the inbox of whoever runs it, so it needs each person's permission through an OAuth app. You create the app once.

Follow the Google connector guide: enable the Gmail API, choose Internal if you're on Google Workspace, add the gmail.modify scope, and create a Web client. Then set these as project secrets, and in .env to test locally:

GOOGLE_CLIENT_ID=...
GOOGLE_CLIENT_SECRET=...

2. Declare the connection

A connection tells Callables the function runs on the account of the person using it. Each person signs in once, and .token is always their own token.

from callables import Connection, Group

google = Connection("google", provider="google", scopes=["gmail.modify"])
gmail = Group("gmail", title="Gmail", connections=[google])

3. Find the mailing lists

Search recent mail, keep the messages that have a List-Unsubscribe header, and group them by sender.

Gmail's search narrows the scan first: mailing lists nearly always say "unsubscribe" in the body. Then the header decides.

QUERY = "newer_than:{days}d unsubscribe -in:sent -in:drafts -in:chats"
HEADERS = ("List-Unsubscribe", "List-Unsubscribe-Post")


def list_messages(client, days):
    ids = client.search(QUERY.format(days=days), limit=2000)
    messages = client.messages(ids, extra_headers=HEADERS)  # format=metadata: headers only, no bodies
    return [m for m in messages if m.headers.get("list-unsubscribe")]

From there, the report is plain Python, the same for both (simplified from the cookbook):

@gmail.deploy(title="Subscriptions", next=[Next(unsubscribe, label="Unsubscribe", sender="email")])
def subscriptions(days: int = 30) -> list[dict]:
    """The mailing lists that emailed you lately, the busiest first, with how much of it you read."""
    client = Gmail(google.token)  # Graph(outlook.token) for Outlook
    by_sender = defaultdict(list)
    for m in list_messages(client, days):
        by_sender[m.sender_email].append(m)
    rows = []
    for address, items in by_sender.items():
        unread = sum(m.unread for m in items)
        rows.append({"email": address, "emails": len(items), "per_week": round(len(items) / days * 7, 1),
                     "read": f"{round(100 * (len(items) - unread) / len(items))}%"})
    return sorted(rows, key=lambda r: -r["emails"])

The next= puts an Unsubscribe button on every row of the results table, filled in with that row's sender.

4. Unsubscribe the best available way

Take the newest email from the sender, read its headers, and use the best method it offers:

def unsubscribe_now(client, sender):
    newest = newest_list_email(client, sender)
    options = unsubscribe_options(newest.headers["list-unsubscribe"], newest.headers.get("list-unsubscribe-post", ""))
    if options.one_click:
        # RFC 8058: a POST with exactly this body. No cookies, no page to click through
        resp = requests.post(options.one_click, data={"List-Unsubscribe": "One-Click"}, timeout=30)
        if resp.ok:
            return f"Unsubscribed from {sender} with their one-click link."
    if options.mailto:
        to, subject, body = parse_mailto(options.mailto)
        client.send(to, subject, body)  # from your own mailbox
        return f"Sent an unsubscribe email to {to}."
    return f"{sender} only offers an unsubscribe page: {options.link}"

Then the unsubscribe callable can clear out what the list already sent:

  • archive: takes the INBOX label off, 1,000 messages per batchModify call. They stay in All Mail.
  • trash: moves them to Trash, where Gmail deletes them after 30 days.

5. Run it on your own inbox

Test locally first with call connect, which signs you in through your browser and keeps the tokens on your machine:

git clone https://github.com/callables-app/callables-cookbook && cd callables-cookbook
pip install callables -r requirements.txt
call connect google                            # sign in to Google once
call gmail subscriptions --days 30
call gmail unsubscribe --sender [email protected] --then archive

6. Share it with your team

Push your fork and deploy the folder as a Callables project. Teammates open Subscriptions, connect their own account the first time, and get their own report, with an Unsubscribe button on every row. Nobody sees anyone else's mail, and nobody handles a password or token. See how scripts that run as each user work.

Staying safe

  • It only uses the header, never links in the email body. A link in the body can be anything, including phishing. The List-Unsubscribe header comes from the sending mail system, and one-click only sends a POST to that address.
  • Unsubscribe emails come from your own account. You'll see them in Sent.
  • Nothing is deleted outright. Archive keeps mail searchable, and Trash or Deleted Items can be undone.
  • Lists can take a few days to stop. In the US, CAN-SPAM gives senders up to 10 business days.
  • Ask for the narrowest access that works. If you only want the report, gmail.readonly or Mail.Read is enough. Unsubscribing by email and clearing out mail need the broader scopes.

The full, tested code, including rate-limit handling for both APIs, is in the cookbook.

Turn your scripts into tools your team can run

Add @deploy to a Python function and push. Your team gets a form, schedules and run history.

See how it works

Keep reading