I have migrated the mailbox from exchange server to office 365.
I have already written the code to connect to office 365 using the credentials and so i am able to read all the email that are there in the inbox.Please find the below code
public async System.Threading.Tasks.Task test()
{
var pcaOptions = new PublicClientApplicationOptions
{
ClientId = ConfigurationManager.AppSettings["appId"],
TenantId = ConfigurationManager.AppSettings["tenantId"],
};
var pca = PublicClientApplicationBuilder
.CreateWithApplicationOptions(pcaOptions).Build();
var ewsScopes = new string[] { "https://outlook.office.com/EWS.AccessAsUser.All" };
try
{
string password = "test";
SecureString sec_pass = new SecureString();
Array.ForEach(password.ToArray(), sec_pass.AppendChar);
sec_pass.MakeReadOnly();
// Make the interactive token request
var authResult = await pca.AcquireTokenByUsernamePassword(ewsScopes, "test@demotenant.com", sec_pass).ExecuteAsync();
//var authResult = await pca.AcquireTokenInteractive(ewsScopes).ExecuteAsync();
// Configure the ExchangeService with the access token
var ewsClient = new ExchangeService();
//ewsClient.ImpersonatedUserId = new ImpersonatedUserId(ConnectingIdType.SmtpAddress, "test@demotenant.onmicrosoft.com");
ewsClient.Url = new Uri("https://outlook.office365.com/EWS/Exchange.asmx");
ewsClient.Credentials = new OAuthCredentials(authResult.AccessToken);
FindItemsResults<Item> result = ewsClient.FindItems(WellKnownFolderName.Inbox, new ItemView(10));
foreach (Item item in result)
{
EmailMessage message = EmailMessage.Bind(ewsClient, item.Id);
String body = message.ConversationTopic;
String from = message.From.Address.ToString();
}
// 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.ToString()}");
}
catch (Exception ex)
{
Console.WriteLine($"Error: {ex.ToString()}");
}
}
Now i am looking to add a listener which can run this code whenever a new mail is received in the inbox. Can someone suggest me on how i can do this.