office365.com SMTP, POP3, IMAP OAuth2 Tips, Hints, and Solutions
This page will be updated as time progresses with what we’ve learned about getting things working with OAuth2 authentication for office365.com using the email protocols: SMTP, POP3, and IMAP.
How do Other Office365 Users Send Email using my App Registered in my Azure Active Directory?
It’s important to understand Tenancy in Azure Active Directory Apps. See this https://learn.microsoft.com/en-us/azure/active-directory/develop/single-and-multi-tenant-apps
When you register your App in Azure Active Directory, you need to choose who will be able to use your App. The choices are:
- Office365 accounts internal to your organization (single-tenant app)
- Office365 accounts internal or external to your organization (multi-tenant)
- Office365 accounts and other personal Microsoft accounts such as Outlook.com (multi-tenant)
For example, when you create your App in the Azure portal, you can see the choices here.
(continue reading below this screenshot…)
Each email account owner using your App will get their initial access token using the Authorization code flow — which is where a browser is displayed, the email account owner logs into his account (if not already) and interactively authorizes your application to do the things specified in the scopes, whatever they may be (such as to send email).
From that point forward, the access token can be used for the operations specified in the scopes, and when the access token expires (typically after an hour) it can be refreshed by your application non-interactively. A typical way to auto-refresh is to catch the error response that indicates an authentication failure, refresh the access token, and then retry — for example, see https://www.example-code.com/csharp/office365_send_email_auto_refresh_token_with_retry.asp
Accessing a Shared Mailbox
The POP3/IMAP/SMTP username for a shared mailbox has this format: Username@DomainName\SharedMailboxAlias