How to bulk unsubscribe from emails with Python
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.
You'll use Microsoft Graph with the Mail.ReadWrite and Mail.Send permissions, which can read, move and send mail in Microsoft 365.
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-ClickThat gives three ways out, from best to worst:
| Method | How it works | Done automatically? |
|---|---|---|
| One-click (RFC 8058) | A POST to the https link. Sent when List-Unsubscribe-Post is present | Yes |
Send a message to the mailto: address, from your own account | Yes | |
| Link only | A web page that may ask you to click a button or fill in a form | No: 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=...Follow the Microsoft connector guide: register a single-tenant app in Entra ID, add the delegated permissions Mail.ReadWrite and Mail.Send, and have an admin grant consent. Then set these as project secrets, and in .env to test locally:
MS_CLIENT_ID=...
MS_CLIENT_SECRET=...
MS_TENANT_ID=...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])from callables import Connection, Group, Secret
outlook = Connection(
"outlook",
provider="microsoft",
scopes=["Mail.ReadWrite", "Mail.Send"],
client_id=Secret("MS_CLIENT_ID"),
client_secret=Secret("MS_CLIENT_SECRET"),
values={"tenant": Secret("MS_TENANT_ID")},
)
mail = Group("outlook", title="Outlook", connections=[outlook])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")]Graph filters by date, and returns each message's headers when you $select them. Sent Items, Drafts, Deleted Items and Junk Email are left out.
SKIP = ("sentitems", "drafts", "deleteditems", "junkemail")
def list_messages(client, days):
skip = client.folder_ids(SKIP)
messages = client.messages("/me/messages", f"receivedDateTime ge {since(days)}", limit=2000,
headers=True) # $select=...,internetMessageHeaders
return [m for m in messages if m.headers.get("list-unsubscribe") and m.folder_id not in skip]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
INBOXlabel off, 1,000 messages perbatchModifycall. They stay in All Mail. - trash: moves them to Trash, where Gmail deletes them after 30 days.
- archive: moves them to the Archive folder, 20 at a time with Graph's JSON batching.
- trash: moves them to Deleted Items, which your organization empties on its own schedule.
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 archivegit clone https://github.com/callables-app/callables-cookbook && cd callables-cookbook
pip install callables -r requirements.txt
call connect outlook # sign in to Microsoft once
call outlook subscriptions --days 30
call outlook unsubscribe --sender [email protected] --then archive6. 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-Unsubscribeheader comes from the sending mail system, and one-click only sends aPOSTto 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.readonlyorMail.Readis 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.
Keep reading
How to share a Python script that runs as each user
Some scripts should use a shared company key. Others should act as the person running them, on their own inbox or calendar. How to build and share the second kind without handling anyone's password or token.
GuidesHow to test OAuth connections locally
Sign in to Gmail, Slack or any OAuth service from your terminal with call connect, then run your functions against your own account before you push.
GuidesHow to automatically extract invoices from Gmail and Outlook into a spreadsheet
Automate invoice processing with Python and Claude: find every invoice attached to your emails, pull the vendor, date, number and total into a CSV, and download all the PDFs as one zip.
