Hi all,
I want to programmatically access a sharedmailbox without username / password (because Microsoft is going to discontinue it.
For this, I'm using an Azure AD Application and I'm generating an Oauth Token;
The code below works well for accessing any mailbox except shared mailboxes.
If I set the ImpersonatedUserId, I receive an error saying "The SMTP address has no mailbox associated with it."
If I don't set it, I receive an error saying "ExchangeImpersonation SOAP header must be present for this type of oauth token".
Can you give me the trick for accessing the shared Mailbox using Oauth.
_service = new ExchangeService(ExchangeVersion.Exchange2013); // (or later)
_service.TraceFlags = TraceFlags.None;
_service.PreAuthenticate = true;
_service.Timeout = 600000; // 10 minutes
string token = GetTokenForUserAsync().Result;
_service.Credentials = new OAuthCredentials(token);
_service.UseDefaultCredentials = false;
string url = "https://outlook.office365.com/ews/Exchange.asmx";
_service.Url = new Uri(url);
_service.ImpersonatedUserId = new ImpersonatedUserId(ConnectingIdType.SmtpAddress, "sharedmailbox@keyman .com");
_fdInbox = Microsoft.Exchange.WebServices.Data.Folder.Bind(_service, new FolderId(WellKnownFolderName.Inbox, "sharedmailbox@keyman .com"));
private async System.Threading.Tasks.Task<string> GetTokenForUserAsync()
{
string domainName = _context.MigrationDefinition.TargetConfiguration.DomainName;
string clientId = _context.MigrationDefinition.TargetConfiguration.ClientID;
string clientSecret = _context.MigrationDefinition.TargetConfiguration.ClientSecret;
string microsoftLoginUrl = AzureURL.GetLoginUrl(_context.MigrationDefinition.TargetConfiguration.ServerRegion);
string loginUrl = string.Format("{0}/{1}", microsoftLoginUrl, domainName);
loginUrl = "https://login.microsoftonline.com/" + domainName + "/oauth2/v2.0/token";
string redirectUri = "https://myapp.azurewebsites.net";
IConfidentialClientApplication app = ConfidentialClientApplicationBuilder.Create(clientId)
.WithClientSecret(clientSecret)
.WithAuthority(loginUrl)
.WithRedirectUri(redirectUri)
.Build();
var ewsScopes = new string[] { "https://outlook.office365.com/.default" };
Microsoft.Identity.Client.AuthenticationResult result = await app.AcquireTokenForClient(ewsScopes).ExecuteAsync();
return result.AccessToken;
}