# Graph Mail via Event Grid Partner Topics: No Webhook Needed

- Date: 2026-11-15
- Author: Jeppe Spanggaard
- Description: Learn how to deliver Microsoft Graph mail notifications to an Azure Function through an Event Grid partner topic, with no public webhook or handshake.
- URL: https://jeppe-spanggaard.dk/blogs/graph-mail-events-event-grid-partner-topic/
- Tags: Microsoft Graph, Azure Functions, Event Grid

## TL;DR

Set a Graph subscription's `notificationUrl` to a magic `EventGrid:?...` URI instead of an HTTPS endpoint, and Graph publishes notifications as CloudEvents into an Event Grid partner topic in your resource group. One-time setup: register the `Microsoft.EventGrid` resource provider, create a partner configuration that authorizes Microsoft Graph API, create the first Graph subscription, then activate the partner topic that appears and point event subscriptions at your `[EventGridTrigger]` functions. No validation handshake anywhere.


I had a working proof of concept for Graph mail notifications the classic way: a public HTTPS endpoint, the validation handshake where Graph POSTs you a token and you echo it back within ten seconds, retry handling, the lot. It worked. It also meant my function app had to expose a public webhook and I owned every piece of delivery plumbing myself.

Then I found out Graph can publish change notifications straight into an Event Grid partner topic in my own subscription. No public endpoint. No handshake. Retries and dead-lettering handled by Event Grid instead of by me.

Credit where it's due: [Julie Turner's post on setting up Azure Event Grid](https://julieturner.net/post/setting-up-azure-event-grid/) is what got me unstuck on the partner configuration dance. She does it for SharePoint list events; this is the same wiring pointed at mailboxes.

If Event Grid itself is new to you, start with my intro to [what Event Grid is and when to use it](/blogs/what-is-azure-event-grid/) - this post builds on it.

## The Magic notificationUrl

Everything hangs on one trick. A Graph subscription normally takes a `notificationUrl` like `https://your-app/api/notifications`. Point it at Event Grid instead:

```csharp
private string NotificationUrl =>
    $"EventGrid:?azuresubscriptionid={_settings.AzureSubscriptionId}" +
    $"&resourcegroup={_settings.ResourceGroup}" +
    $"&partnertopic={_settings.PartnerTopicName}" +
    $"&location={_settings.Location}";
```

**What's happening here?**

1. The `EventGrid:` scheme tells Graph not to POST to a webhook at all, but to publish into Event Grid as a partner.
2. The query parameters say where: your Azure subscription, resource group, a partner topic name of your choosing, and the region.
3. The topic doesn't have to exist yet. Graph creates it on first use, which is a step in the setup order below.
4. The `partnertopic` name is what routes. All my Graph subscriptions (hundreds of mailboxes, two folders each) use the same name and land on one shared topic. You do not create a topic per mailbox.

## The Partner Configuration Dance (One-Time Setup)

The order matters, and half my confusion came from not knowing it. Four steps:

**1. Register the resource provider.** `Microsoft.EventGrid` must show Registered under your subscription's resource providers. While you're in there, ignore `Microsoft.ResourceGraph` and `Microsoft.GraphServices` - the names are misleading and they're unrelated.

**2. Create a partner configuration.** In the resource group where your functions live, create an Event Grid Partner Configuration (there's exactly one per resource group, named "default") and add **Microsoft Graph API** as an authorized partner. The authorization has an expiration window, and here's the part that isn't obvious: the window only limits when Graph may *create* partner topics. Existing topics and subscriptions keep working after it lapses. Set it to something like 30 days to cover your setup period and forget about it until you need a new topic.

![Partner configuration with Microsoft Graph API authorized](/images/graph-mail-events-event-grid-partner-topic-1.png)

**3. Create the first Graph subscription.** With the magic URL from above:

```csharp
var request = new Subscription {
    ChangeType = "created",
    NotificationUrl = NotificationUrl,
    LifecycleNotificationUrl = NotificationUrl,
    Resource = $"users/{mailbox}/mailFolders('Inbox')/messages",
    ClientState = _settings.ClientState,
    ExpirationDateTime = DateTimeOffset.UtcNow.AddMinutes(1380),
};

var created = await graph.Subscriptions.PostAsync(request);
```

**What's happening here?**

1. `NotificationUrl` and `LifecycleNotificationUrl` both point at the partner topic. Lifecycle events (like reauthorization requests) arrive on the same topic as mail events, distinguished by event type.
2. `ChangeType = "created"` covers both incoming and outgoing mail - sending a message produces a `created` in SentItems, so subscribe to both folders per mailbox.
3. `ClientState` is a secret Graph echoes back in every notification. The handler verifies it on every event.
4. The short expiration isn't an accident. My setup uses rich notifications (`IncludeResourceData = true` plus an encryption certificate), where the encrypted message payload rides along with the event so the handler makes zero Graph read calls on the hot path. The trade-off: max subscription lifetime drops to 1,440 minutes, so renewal becomes a daily chore that a timer function owns. Worth it, but it's a real operational duty you're signing up for.

**4. Activate the topic and wire it up.** After that first subscription call, the partner topic materializes in your resource group in a "Pending activation" state. Activate it, then create event subscriptions on it pointing at your functions - I have two: one to the mail handler, one to a reauthorization handler that renews Graph subscriptions when a `Microsoft.Graph.SubscriptionReauthorizationRequired` event arrives. The portal lets you filter each subscription by event type; I skipped the filters and let each function check the event type in code instead. Both functions receive everything, each drops what isn't for it, and the routing decision is code I can read instead of portal config I have to remember exists.

![Creating an event subscription to an Azure Function](/images/graph-mail-events-event-grid-partner-topic-2.png)

While you're on that blade: enable dead-lettering to a blob container on both event subscriptions. Failed deliveries retry for about 24 hours, then land there as blobs with the failure reason attached. Getting alerted when that happens is the next post in this series.

## The Event Grid Trigger Function

The receiving end is refreshingly boring:

```csharp
[Function(nameof(MailEventHandler))]
public async Task Run([EventGridTrigger] CloudEvent cloudEvent, CancellationToken cancellationToken) {
    var notification = cloudEvent.Data?.ToObjectFromJson<ChangeNotification>(JsonDefaults.CaseInsensitive);
    if (notification is null || string.IsNullOrWhiteSpace(notification.SubscriptionId)) {
        logger.LogWarning("Event {EventId} carried no usable notification payload; dropping.", cloudEvent.Id);
        return;
    }

    if (!string.Equals(notification.ClientState, options.Value.ClientState, StringComparison.Ordinal)) {
        logger.LogWarning("Dropping event for subscription {SubscriptionId}: clientState mismatch.",
            notification.SubscriptionId);
        return;
    }

    // Look up which mailbox and folder this subscription belongs to, then do the actual work.
}
```

**What's happening here?**

1. Bind `Azure.Messaging.CloudEvent`, not `EventGridEvent`. Partner topics deliver the CloudEvents schema, and the wrong type gives you confusing deserialization failures.
2. There is no validation handshake code. None. The handshake that plain Graph webhooks require is handled entirely by the partner topic plumbing.
3. `clientState` is checked on every event with an ordinal compare. It's the proof the event traces back to a subscription you created.
4. Note what happens on bad input: log and return, not throw. A poison event that throws gets redelivered for 24 hours. Save the exceptions for failures that are actually transient, so Event Grid's retries work for you instead of against you.

The mapping from `subscriptionId` to mailbox and folder lives in a small Azure Table - Graph tells you which subscription fired, and the table tells you whose mail that is.

## Testing the Trigger Locally (Without Sending 50 Mails)

You can poke a locally running Event Grid trigger directly. The functions host exposes the delivery endpoint locally:

```
POST http://localhost:7071/runtime/webhooks/eventgrid?functionName=MailEventHandler
aeg-event-type: Notification
Content-Type: application/json

{ ...a sample CloudEvent... }
```

The `aeg-event-type: Notification` header is the part everyone forgets, and the error you get without it tells you nothing useful. Ask me how I know.

## Gotchas

- **Check the event type in code.** The mail types are documented in the [Outlook events reference](https://learn.microsoft.com/en-us/azure/event-grid/outlook-events) (`Microsoft.Graph.MessageCreated` and friends), but the most honest verification is still sending yourself a test mail on the activated topic and reading the `type` off the event. Trust what actually arrives.
- **The partner configuration expiration only gates topic creation.** Don't panic-renew it for a running system; renew it when you need Graph to create a new topic.
- **Both notification URLs, same value.** Forget `LifecycleNotificationUrl` and reauthorization events go nowhere, and your subscriptions quietly die at their expiry instead of renewing.
- **Rich notifications shorten subscription lifetime to a day.** `IncludeResourceData` is great for the hot path, but it commits you to daily renewals and certificate rotation. Budget a reconciler timer for it from day one.
- **At-least-once still applies.** Same event, delivered twice, is normal. Dedupe on the message id.

## Wrapping Up

Point a Graph subscription's `notificationUrl` at `EventGrid:?...`, authorize Graph as a partner once, activate the topic that appears, and mail notifications become plain Event Grid events hitting a plain `[EventGridTrigger]` function. No public webhook, no handshake, and delivery plumbing that's Azure's problem instead of mine. Rule of thumb: if a service can publish to a partner topic, take that over hosting a webhook every time.

