1 year ago
#373664
Roxana
EWS API to access Office365 with oAuth via SSIS/C#
I have a SSIS package that is using EWS API to access a mailbox(office365) and read emails attachment. I am using Script Task and C# .The way I am doing it right now is to pass the password of the mailbox (basic authentication). Based on the Microsoft new policy I need to move the email sends from EWS to Modern authentication. Microsoft will be preventing authentication through basic protocols such as EWS in October 2022.
I've followed this article https://learn.microsoft.com/en-us/exchange/client-developer/exchange-web-services/how-to-authenticate-an-ews-application-by-using-oauth#add-code-to-get-an-authentication-token I have two question now! How I am supposed to add Microsoft.Identity.Client 4.22.0 dll to the script task reference.By using NuGet management the dll keeps disappearing! I've tried to unzip the NuGet package and add the dll manually but still gives me error when running the package.
I 've wrote the following code :
private static async System.Threading.Tasks.Task Main(string[] args)
{
var cca = ConfidentialClientApplicationBuilder.Create(ConfigurationManager.AppSettings["appId"]).WithClientSecret(ConfigurationManager.AppSettings["clientSecret"])
.WithTenantId(ConfigurationManager.AppSettings["tenantId"])
.Build();
var ewsScopes = new string[] { "https://outlook.office365.com/.default" };
try
{
var authResult = await cca.AcquireTokenForClient(ewsScopes).ExecuteAsync();
// Configure the ExchangeService with the access token
var ewsClient = new ExchangeService();
ewsClient.Url = new Uri("https://outlook.office365.com/EWS/Exchange.asmx");
ewsClient.Credentials = new OAuthCredentials(authResult.AccessToken);
ewsClient.ImpersonatedUserId =
new ImpersonatedUserId(ConnectingIdType.SmtpAddress, "mailbox@domain.com");
//Include x-anchormailbox header
ewsClient.HttpHeaders.Add(" X-AnchorMailbox", "mailbox@domain.com");
// Make an EWS call
var folders = ewsClient.FindFolders(WellKnownFolderName.MsgFolderRoot, new FolderView(10));
foreach (var folder in folders)
{
Console.WriteLine($"Folder: {folder.DisplayName}");
}
}
catch (MsalException ex)
{
Console.WriteLine($"Error acquiring access token: {ex}");
}
catch (Exception ex)
{
Console.WriteLine($"Error: {ex}");
}
if (System.Diagnostics.Debugger.IsAttached)
{
Console.WriteLine("Hit any key to exit...");
Console.ReadKey();
}
}
And I've put AppID,TokenID and clientSecret in the app.config.
The problem I have now is how to callstatic async System.Threading.Tasks.Task Main(string[] args)
from public void Main()
in the script task ? And I have no idea if I am following the right path! Anyone have done this befotr and could please shed some light?
c#
ssis
oauth
office365
exchangewebservices
0 Answers
Your Answer