AI Agents8 min read

Email Classification Agent with Microsoft Graph and an LLM

Build an agent that reads Outlook mail through Microsoft Graph, labels it with an LLM, then sets categories, flags and folders, with review for unsure labels.

By AI Agents DirectoryLast checked
Green characters of computer code on a dark screen

An email triage agent on Microsoft 365 needs three things: a way to read Outlook mail, a model that turns a message into a label, and a way to write that label back so it shows up in Outlook. Microsoft Graph covers the first and third parts. A large language model with structured output covers the middle. This guide walks through the permissions to ask for, a compact Python example built from Microsoft’s SDK snippets and Anthropic’s structured outputs docs, how to hear about new mail without polling, and where a human should check the agent’s work. It is the Outlook counterpart to our Gmail and Drive API guide.

What the agent does

  1. Reads new messages from a mailbox folder (subject, preview, existing categories).
  2. Sends the text to an LLM and gets back a fixed JSON object: a label, an urgency flag and a confidence level.
  3. Writes the result into the mailbox: sets Outlook categories, flags urgent mail for follow-up, and moves some labels to a folder.
  4. Leaves anything the model is unsure about in the inbox with a “Needs review” category for a person to sort.

Every action here is a plain Graph call, so the same pattern fits any agent framework. For the general shape of wiring tools to APIs, see connecting an AI agent to APIs.

Register the app and choose permissions

Register the app in the Microsoft Entra admin center. The registration quickstart recommends the single-tenant option for most apps; note the Application (client) ID, which your code uses.

Next, decide who the agent acts as. The Python SDK README puts it simply: delegated permissions are for an app where a user signs in, and application permissions are for an app that runs in the background with nobody signed in. Microsoft’s permissions overview calls application permissions highly privileged and says delegated access is the least-privilege choice when it meets your needs. A personal assistant for one user should be delegated. A shared triage mailbox processed by a service is the usual case for application permissions.

The mail permissions that matter, from the permissions reference and the API pages:

PermissionWhat it allowsNeeded for
Mail.ReadBasicRead mail except the body, body preview, attachments and extended propertiesListing messages, if headers alone are enough
Mail.ReadRead mail, including bodiesClassifying on content; subscribing to new mail
Mail.ReadWriteCreate, read, update and delete mail; no sendingSetting categories and flags, moving messages
MailboxSettings.ReadWriteCreate, read, update and delete mailbox settingsAdding categories to the master list

The update and move calls both list Mail.ReadWrite, so a classifier that writes anything back needs it. Note what you do not need: no Mail.Send. The application version of Mail.Read requires admin consent; the delegated version does not.

Limit an app-only agent to the right mailboxes

Mail.ReadWrite as an application permission covers every mailbox in the organisation. Exchange Online has a fix: RBAC for Applications, which replaces the older application access policies. An Exchange admin creates a service principal pointer to the Entra app, then assigns a role such as Application Mail.ReadWrite scoped by a management scope or an administrative unit:

New-ManagementRoleAssignment -App <service-principal-object-id> -Role "Application Mail.ReadWrite" -CustomResourceScope "Triage mailboxes"
Test-ServicePrincipalAuthorization -Identity <service-principal-object-id> -Resource [email protected]

The trap: grants in Entra ID and Exchange are combined. If the app still holds an unscoped Mail.ReadWrite grant in Entra ID, the Exchange scope does nothing. Remove the Entra grant. Our security and privacy hub lists tools that help audit app permissions.

The code

Install the SDKs with pip install msgraph-sdk anthropic. The Graph SDK needs Python 3.10 or later and is async by default. The example below uses app-only auth with ClientSecretCredential, as in the SDK README, and Anthropic’s messages.parse with a Pydantic model, which their docs recommend for structured outputs.

import asyncio
from typing import Literal

from anthropic import Anthropic
from azure.identity.aio import ClientSecretCredential
from kiota_abstractions.base_request_configuration import RequestConfiguration
from msgraph import GraphServiceClient
from msgraph.generated.models.followup_flag import FollowupFlag
from msgraph.generated.models.followup_flag_status import FollowupFlagStatus
from msgraph.generated.models.message import Message
from msgraph.generated.users.item.mail_folders.item.messages.messages_request_builder import (
    MessagesRequestBuilder,
)
from msgraph.generated.users.item.messages.item.move.move_post_request_body import (
    MovePostRequestBody,
)
from pydantic import BaseModel

MAILBOX = "[email protected]"
REVIEW_CATEGORY = "Needs review"
FOLDERS = {"Billing": "<billing-folder-id>"}  # move only these labels


class Triage(BaseModel):
    label: Literal["Billing", "Support", "Sales", "Newsletter", "Other"]
    urgent: bool
    confidence: Literal["high", "medium", "low"]


llm = Anthropic()
graph = GraphServiceClient(
    credentials=ClientSecretCredential("TENANT_ID", "CLIENT_ID", "CLIENT_SECRET"),
    scopes=["https://graph.microsoft.com/.default"],
)


def classify(subject: str, preview: str) -> Triage:
    response = llm.messages.parse(
        model="claude-opus-5-5",
        max_tokens=256,
        output_format=Triage,
        messages=[{
            "role": "user",
            "content": f"Classify this email.\nSubject: {subject}\nPreview: {preview}",
        }],
    )
    return response.parsed_output


async def triage_inbox():
    query = MessagesRequestBuilder.MessagesRequestBuilderGetQueryParameters(
        select=["subject", "bodyPreview", "categories"], top=25,
    )
    page = await graph.users.by_user_id(MAILBOX).mail_folders.by_mail_folder_id(
        "inbox").messages.get(RequestConfiguration(query_parameters=query))
    for msg in page.value:
        if msg.categories:  # already handled
            continue
        result = classify(msg.subject or "", msg.body_preview or "")
        item = graph.users.by_user_id(MAILBOX).messages.by_message_id(msg.id)
        if result.confidence != "high":
            await item.patch(Message(categories=[REVIEW_CATEGORY, result.label]))
            continue
        update = Message(categories=[result.label])
        if result.urgent:
            update.flag = FollowupFlag(flag_status=FollowupFlagStatus.Flagged)
        await item.patch(update)
        if result.label in FOLDERS:
            await item.move.post(MovePostRequestBody(destination_id=FOLDERS[result.label]))


asyncio.run(triage_inbox())

A few details behind those calls:

  • Listing. The list messages call returns 10 messages per page unless you set $top (allowed range 1 to 1000), and Microsoft suggests $select to keep responses small. For later pages, follow @odata.nextLink as-is rather than editing its $skip. bodyPreview holds the first 255 characters of the body as text, which is often enough to classify. For the full body, add a Prefer: outlook.body-content-type="text" header, since bodies come back as HTML by default.
  • Categories. You apply a category by putting its display name in the message’s categories collection. Creating the names once in the user’s master category list gives each a colour (one of 25 presets); names must be unique and cannot be renamed later.
  • Flags. The flag property takes a followupFlag whose status is notFlagged, flagged or complete. If you set a due date you must set a start date too, or the call returns 400.
  • Moving. A move puts a new copy in the target folder and removes the original, and the call returns that new message. Set categories first, then move, and use the returned object rather than the old ID afterwards. The destination is a folder ID or a well-known folder name.
  • Schema limits. Anthropic’s structured outputs support enum, which is what Literal becomes, but not numeric limits such as minimum or maximum. That is one reason the example uses a three-level confidence label instead of a float. If the model refuses, the response has stop_reason: "refusal" and may not match the schema, so route those to review too.

React to new mail instead of polling

Microsoft’s throttling guidance warns that constant polling makes throttling more likely and points to change notifications and change tracking instead. Use both.

Change notifications. Create a subscription on the inbox with changeType set to created, a notificationUrl you host and a secret clientState. When you create it, Graph sends a validationToken to your URL, and you must echo it back as plain text with a 200 within 10 seconds. After that, return a 2xx within 3 seconds for each notification, or Graph retries for up to 4 hours; Microsoft suggests queueing the work and returning 202. Check clientState on every notification. For Outlook messages, a subscription lasts at most 10,080 minutes (under seven days), or 1,440 minutes if it includes resource data, so renew on a schedule. Delegated subscriptions only cover the signed-in user’s own mailbox, and each mailbox can have at most 1,000 active Outlook subscriptions across all apps. Subscribe to lifecycle notifications too, which warn you about reauthorization, removed subscriptions and missed notifications.

Subscribe to created only. Setting categories or a flag changes the message, and an updated subscription would fire on the agent’s own writes.

Delta query. A delta query on /mailFolders/{id}/messages/delta returns every change since the last @odata.deltaLink you saved. It works per folder, and you can ask for changeType=created only. Run it after a restart or a missed-notification event so nothing slips through.

Throttling

Outlook limits apply per app per mailbox: 10,000 requests in 10 minutes and four concurrent requests, according to the service limits page. Hitting a limit returns 429 with a Retry-After header; wait that many seconds, then retry. The Graph SDKs already include retry handlers that honour the header. One classified message here costs one to three Graph calls (patch, maybe move) plus one model call, so a busy shared mailbox still fits, but process mailboxes in parallel rather than firing many requests at one mailbox.

Human review for low-confidence labels

The model will sometimes be wrong, and a wrong move hides mail. The example handles that in three ways:

  • Low or medium confidence: the message stays in the inbox with “Needs review” plus the suggested label, so a person sees the guess and fixes it in Outlook.
  • Only safe labels move. Moving is limited to labels in FOLDERS. Newsletters can be categorised without leaving the inbox until you trust the classifier.
  • No deletes, no sending. The agent never calls delete or send, and Mail.ReadWrite cannot send mail anyway.

Log each decision (message ID, label, confidence, action) so reviewers can spot repeated mistakes and you can adjust the label set or prompt. Treat email text as untrusted input: the model only returns a label from a fixed list, and the code, not the model, decides which Graph call to make.

For more automation tools, browse the productivity and automation hub.

#AI agents#Microsoft Graph#Outlook#email automation#structured outputs
AI

Written by AI Agents Directory

Editorial team

Facts in this guide are checked against official documentation and repositories, which are linked in the article.