I've created an Azure AD application and I want to send emails on behalf of some users(limited list) in a daemon service. I use Azure AD v2.0 endpoint to authenticate to the Microsoft Office 365. When I give "Send mail as any user" permission to the app and use "https://outlook.office365.com/api/v2.0/users/{user}/sendmail", It works fine. Is there any way to send mail as a user without giving this permission and user interaction? This permission is too wide. How can I limit it to some users? Thanks
2 Answers
A bit late on the ball, but there seems to be an answer for this now. Here are some docs limiting access to certain groups.
According to your description, I suppose you have two questions.
First question, you want to send mail as a user without user interaction.
Second question, you want to limit the sender of mail to some users, instead of all user.
For your question #1, we can refer to this document. As the description of the content, we can get access without a user.
Based on my test, we can try the following steps:
Step 1, we should get administrator consent:
app.UseOpenIdConnectAuthentication(new OpenIdConnectAuthenticationOptions
{
ClientId = clientId,
Authority = authority,
RedirectUri = redirectUri,
PostLogoutRedirectUri = redirectUri,
Scope = "openid profile",
ResponseType = "id_token",
TokenValidationParameters = new TokenValidationParameters { ValidateIssuer = false, NameClaimType = "name" },
Notifications = new OpenIdConnectAuthenticationNotifications
{
AuthenticationFailed = this.OnAuthenticationFailedAsync,
SecurityTokenValidated = this.OnSecurityTokenValidatedAsync
}
});
ConfidentialClientApplication daemonClient = new ConfidentialClientApplication(Startup.clientId, string.Format(AuthorityFormat, tenantId), Startup.redirectUri,
new ClientCredential(Startup.clientSecret), null, appTokenCache.GetMsalCacheInstance());
AuthenticationResult authResult = await daemonClient.AcquireTokenForClientAsync(new[] { MSGraphScope });
We can refer to the simple code.
Step 2, we can use the Graph API to send email.
For your question #2, we can set some email addresses to send emails, such as '[email protected]'. Then we can user API: POST /users/{id | userPrincipalName}/sendMail
like this:
POST https://graph.microsoft.com/v1.0/[email protected]/sendMail. For more detail, we can refer to this document.