Zero Labs
Industry News / AI

I Gave Claude Access to My Desktop Outlook Without Touching the Microsoft API

Source · Towards AI By Poorna Reddy

From the publisher’s feed, collected in the ZeroLabs newsroom.

How a 150-line Python script using macOS Accessibility APIs turned my Mac’s Outlook app into a fully AI-readable inbox no OAuth, no permissions headache, no Graph API token.Every few months I try again to get Claude to help me with my emails. Every few months I run into the same wall: Microsoft’s Graph API requires an Azure app registration, an OAuth flow, admin consent for enterprise tenants, and — depending on your company’s IT policy — a support ticket that takes two weeks to resolve. By then, I’ve given up and gone back to manually copy-pasting emails into Claude.Then I found a different angle. macOS has had a powerful accessibility API since the early days of OS X. It’s the same system that screen readers use. Any app running on your Mac including Outlook exposes its entire UI element tree to this API. That means you can programmatically read the subject, sender, timestamp, and body of every visible email in Outlook without touching Microsoft’s servers at all.I built a small Python agent that does exactly this: it uses the macOS Accessibility API to scan your open Outlook app, extract all visible emails, deduplicate them, and save them as clean markdown files on your desktop. You can then point Claude — or any other LLM — at those files and have a full conversation about your inbox.The approach: use Mac’s native Accessibility API (the same one VoiceOver uses) to read Outlook’s UI directly. No API keys. No OAuth. No admin consent. Just Python and macOS permissions.This article walks through the architecture, the key code, and the practical setup. The full source is open source on GitLab at https://gitlab.com/timo2026/outlook-email-scanner — MIT licensed, 16 commits, built fresh in April 2026.Why not just use the Microsoft Graph API?The Microsoft Graph API is the proper, Microsoft-sanctioned way to read Outlook emails programmatically. It works well in enterprise pipelines. But it has a setup cost that makes it impractical for personal productivity use:• You need an Azure Active Directory app registration• Enterprise accounts typically need IT admin consent for mail-reading scopes• The OAuth token flow requires a redirect URI, client secrets, and refresh token management• In many corporate environments, the Mail.Read permission is restricted by policyFor a software engineer building a personal tool on their work Mac, none of these are insurmountable — but all of them take time, and most of them depend on someone else’s approval. The macOS Accessibility approach bypasses all of this because it doesn’t touch the network at all. It reads what’s already rendered on your screen.How the macOS Accessibility API worksmacOS exposes every visible UI element through the Accessibility framework under the NSAccessibility protocol. Each element — a button, a text field, a list item — is an AXElement with attributes like AXTitle, AXValue, AXRole, and AXChildren. The hierarchy mirrors the visual structure of the app: the Outlook window contains a message list, each list item is an email row, each row has child elements for subject, sender, and preview text.Python can query this hierarchy through the `atomacos` library (a modern successor to the older `pyatomac` and `AppScript` bindings). Once macOS has granted accessibility access to your Python process (a one-time permission in System Settings), you can walk the entire Outlook element tree programmatically.The element tree for an Outlook emailWhen you open Outlook on a Mac, the email list panel is a scrollable AXList. Each row is an AXCell containing several AXStaticText elements. The structure looks roughly like this:AXApplication (Microsoft Outlook)└── AXWindow└── AXSplitGroup├── AXScrollArea (folder list / nav)└── AXScrollArea (email list)└── AXList├── AXCell [email row 0]│ ├── AXStaticText → sender name│ ├── AXStaticText → subject│ ├── AXStaticText → date/time│ └── AXStaticText → preview snippet├── AXCell [email row 1]└── …The body of the selected email appears in a separate AXWebArea or AXTextArea depending on whether you’re viewing HTML or plain text. The agent reads the list first to get all visible emails, then programmatically clicks each one to load the body, reads it, then moves on.Architecture of the scannerThe project has four main components that work together:WhatDetailoutlook_scanner.pyCore agent. Uses atomacos to traverse the Outlook element tree, extracts email metadata and body text, and manages the scanning loop.markdown_writer.pyConverts each extracted email dict into a clean .md file. Handles filename sanitisation, timestamp formatting, and YAML front-matter for AI context.deduplicator.pyTracks a local SHA-256 hash of each email’s (sender + subject + date) tuple. Skips emails already written to disk on subsequent runs.run_scanner.pyEntry point. Accepts CLI args for output directory and max email count. Calls the scanner, deduplicator, and writer in sequence.The core codeStep 1 — Grant accessibility permissionBefore any code will work, macOS needs to trust your Python process. Do this once:System Settings → Privacy & Security → AccessibilityAdd your terminal app (Terminal, iTerm2, VS Code, etc.)This grants the running Python process permission to query UI elements.Test that permission is active:python3 -c “import atomacos; print(atomacos.getAppRefByBundleId(‘com.microsoft.Outlook’))”# If you see you’re ready.# If you see a permission error, revisit System Settings.Step 2 — Connect to Outlook and find the email list# pip install atomacosimport atomacosimport timedef get_outlook_app():“””Return a reference to the running Outlook app.”””try:app = atomacos.getAppRefByBundleId(‘com.microsoft.Outlook’)return appexcept Exception as e:raise RuntimeError(‘Could not find Outlook. Is it open and in the foreground?’) from edef find_email_list(app):“””Walk the AX element tree to find the AXList that holds email rows.Outlook’s UI structure can shift slightly between versions,so we search recursively rather than hardcoding a fixed path.“””def find_ax_list(element, depth=0):if depth > 8: # don’t recurse indefinitelyreturn Noneif element.AXRole == ‘AXList’:children = element.AXChildren or []# The email list has AXCell children; filter out nav listscells = [c for c in children if c.AXRole == ‘AXCell’]if len(cells) > 2:return elementfor child in (element.AXChildren or []):result = find_ax_list(child, depth + 1)if result:return resultreturn Nonewindows = app.AXWindowsif not windows:raise RuntimeError(‘No Outlook window found. Make sure Outlook is open.’)return find_ax_list(windows[0])Step 3 — Extract metadata from each email rowdef extract_email_metadata(cell):“””Given an AXCell (one email row), extract sender, subject,timestamp, and preview snippet from its AXStaticText children.“””texts = []for child in (cell.AXChildren or []):if child.AXRole == ‘AXStaticText’:val = child.AXValueif val and val.strip():texts.append(val.strip())# Outlook renders: [sender, subject, date, preview] in that order.# This order is consistent across Outlook 16.x on macOS.return {‘sender’: texts[0] if len(texts) > 0 else ‘Unknown’,‘subject’: texts[1] if len(texts) > 1 else ‘(no subject)’,‘date’: texts[2] if len(texts) > 2 else ‘’,‘preview’: texts[3] if len(texts) > 3 else ‘’,‘body’: ‘’, # filled in next step}Step 4 — Click each email to load the bodydef extract_email_body(app):“””After clicking an email row, Outlook loads the body in the reading pane.We find the AXWebArea (HTML emails) or AXTextArea (plain text)and read its AXValue.“””time.sleep(0.6) # allow the reading pane to renderdef find_body_element(element, depth=0):if depth > 10:return Nonerole = element.AXRoleif role in (‘AXWebArea’, ‘AXTextArea’, ‘AXScrollArea’):val = getattr(element, ‘AXValue’, None)if val and len(val.strip()) > 50: # ignore tiny elementsreturn val.strip()for child in (element.AXChildren or []):result = find_body_element(child, depth + 1)if result:return resultreturn Nonewindows = app.AXWindowsbody = find_body_element(windows[0]) if windows else Nonereturn body or ‘(body not readable — try opening the email in its own window)’def scan_emails(max_emails=50, output_dir=’~/Desktop/emails’):“””Main scanning loop.”””import osoutput_dir = os.path.expanduser(output_dir)os.makedirs(output_dir, exist_ok=True)app = get_outlook_app()email_list = find_email_list(app)if not email_list:print(‘Could not locate email list. Make sure the inbox is visible.’)returncells = [c for c in email_list.AXChildren if c.AXRole == ‘AXCell’]cells = cells[:max_emails]results = []for i, cell in enumerate(cells):metadata = extract_email_metadata(cell)print(f’[{i+1}/{len(cells)}] Reading: {metadata[“subject”][:60]}’)# click the row to load the bodytry:cell.AXPress()except Exception:pass # some rows don’t support press; body stays emptymetadata[‘body’] = extract_email_body(app)results.append(metadata)return resultsStep 5 — Write each email to a markdown fileimport hashlib, re, osfrom datetime import datetimeSEEN_HASHES_FILE = os.path.expanduser(‘~/.outlook_scanner_seen.txt’)def load_seen_hashes():if not os.path.exists(SEEN_HASHES_FILE):return set()with open(SEEN_HASHES_FILE) as f:return set(line.strip() for line in f if line.strip())def save_hash(h):with open(SEEN_HASHES_FILE, ‘a’) as f:f.write(h + ‘\n’)def email_hash(email):key = f”{email[‘sender’]}|{email[‘subject’]}|{email[‘date’]}”return hashlib.sha256(key.encode()).hexdigest()[:16]def write_email_md(email, output_dir):Write one email dict to a .md file with YAML front-matter.safe_subject = re.sub(r’[^\w\s-]’, ‘’, email[‘subject’])[:60].strip()safe_subject = re.sub(r’\s+’, ‘_’, safe_subject)filename = f”{safe_subject}_{email_hash(email)}.md”filepath = os.path.join(output_dir, filename)content = f””” — -from: {email[‘sender’]}subject: {email[‘subject’]}date: {email[‘date’]}scanner: outlook-email-scanner— -# {email[‘subject’]}**From:** {email[‘sender’]}**Date:** {email[‘date’]}— -{email[‘body’]}“””with open(filepath, ‘w’, encoding=’utf-8') as f:f.write(content)return filepathdef write_all_emails(emails, output_dir=’~/Desktop/emails’):output_dir = os.path.expanduser(output_dir)seen = load_seen_hashes()written, skipped = 0, 0for email in emails:h = email_hash(email)if h in seen:skipped += 1continuepath = write_email_md(email, output_dir)save_hash(h)written += 1print(f’ ✓ Saved: {os.path.basename(path)}’)print(f’\nDone. {written} new emails saved, {skipped} duplicates skipped.’)print(f’Output: {output_dir}’)Running the scanner end-to-end1. Install dependenciespip install atomacos2. Clone the repogit clone https://gitlab.com/timo2026/outlook-email-scanner.gitcd outlook-email-scanner3. Grant accessibility permission (System Settings → Privacy → Accessibility)Add your terminal application. This is a one-time step.4. Open Outlook and navigate to your inbox5. Runpython3 run_scanner.py — max-emails 30 — output ~/Desktop/emailsExpected output:# [1/30] Reading: Project update for Q2…# [2/30] Reading: RE: Vendor meeting Thursday…# …# Done. 28 new emails saved, 2 duplicates skipped.# Output: /Users/yourname/Desktop/emailsAfter the scan, your Desktop/emails folder will contain files like:emails/├── Project_update_for_Q2_a3f2b19c.md├── RE_Vendor_meeting_Thursday_9d1e4a07.md├── Budget_approval_needed_c82f3d11.md└── …Now give Claude your emailsWith the markdown files on your desktop, you have two options depending on how you work with Claude.Option A — Claude.ai Projects (recommended)Create a Project in Claude.ai, upload the markdown files from your emails folder, and Claude will have context-aware access to your entire inbox dump. You can then ask things like:• “Which emails need a response before end of day?”• “Summarise all threads where budget is mentioned.”• “Draft a reply to the vendor meeting email, keeping it under 100 words.”• “Flag any emails that seem to require action from me specifically.”Option B — Claude Desktop with a local folderIf you’re using the Claude desktop app and have set up MCP file access, you can point Claude directly at the output directory. The YAML front-matter in each file gives Claude structured metadata (from, subject, date) to work with in addition to the body text.Limitations and honest caveatsThis approach works well, but it has three real constraints you should know going in.1. Outlook must be open and visibleThe Accessibility API reads what’s rendered on screen. If Outlook is minimised, behind another window, or the inbox isn’t the active view, the scanner either errors out or reads stale content. The practical fix is to run the scanner immediately after checking your email in the morning, rather than scheduling it as a background task.2. Rendering is sensitive to Outlook versionMicrosoft updates Outlook for Mac regularly, and UI structure can shift between versions. The recursive AXList search in the code above is more robust than hardcoded paths, but if you upgrade Outlook and the scanner stops finding emails, the AXRole hierarchy may have changed. The repo includes a diagnostic script (`debug_tree.py`) that prints the full element tree, which makes re-adapting the scanner a 10-minute task rather than a guessing game.3. Accessibility permission is broadThe macOS Accessibility permission you grant applies to your terminal process generally, not just to this script. This is a standard constraint of the macOS Accessibility framework. If you’re security-conscious, run the scanner from a dedicated terminal profile and revoke the permission when not in use.Why this matters beyond emailThe broader point here is that macOS’s Accessibility API is a largely underused surface for AI integration work. Every native Mac app — Calendar, Contacts, Notes, Finder, even most Electron apps — exposes its element tree through the same NSAccessibility protocol. The same pattern used here can be adapted to:• Reading calendar events from the Mac Calendar app without a Google or Apple CalDAV integration• Extracting Slack message content from the Slack desktop app without API tokens (useful for searching archived channels that the API doesn’t expose)• Scraping content from any desktop app for which no official API existsThe Accessibility API was designed for assistive technology, but it turns out to be a very practical tool for building local AI integrations that bypass cloud authentication entirely. The email scanner is a specific case of a more general pattern: treat your desktop apps as data sources, not as walled gardens.The real unlock here isn’t email specifically. It’s the idea that any Mac app with a rendered UI is, in principle, machine-readable via NSAccessibility — with nothing more than a Python library and a one-time system permission.Getting started1. Clone the repo: https://gitlab.com/timo2026/outlook-email-scanner2. Install atomacos: pip install atomacos3. Grant accessibility permission to your terminal in System Settings → Privacy & Security → Accessibility4. Open Outlook and navigate to your inbox5. Run: python3 run_scanner.py — max-emails 506. Upload the output markdown files to a Claude Project and start asking questionsThe full repo includes a README with setup instructions, a `debug_tree.py` diagnostic, and a `requirements.txt`. The MIT license means you can adapt it freely for your own use cases.About the authorPoorna Reddy builds AI automation tools and enterprise data pipelines. This article is based on an open-source project available at https://gitlab.com/timo2026/outlook-email-scanner.I Gave Claude Access to My Desktop Outlook Without Touching the Microsoft API was originally published in Towards AI on Medium, where people are continuing the conversation by highlighting and responding to this story.