FindItemsResults<Item> findMailResults = null;
public async System.Threading.Tasks.Task<FindItemsResults<Item>> GetMail()
{
try
{
string appId = ConfigurationManager.AppSettings["appId"];
string clientSecret = ConfigurationManager.AppSettings["clientSecret"];
string tenantId = ConfigurationManager.AppSettings["tenantId"];
var cca = ConfidentialClientApplicationBuilder
.Create(appId)
.WithClientSecret(clientSecret)
.WithTenantId(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, ConfigurationManager.AppSettings["Email"]);
//Include x-anchormailbox header
ewsClient.HttpHeaders.Add("X-AnchorMailbox", ConfigurationManager.AppSettings["Email"]);
// Make an EWS call
var folders = ewsClient.FindFolders(WellKnownFolderName.MsgFolderRoot, new FolderView(10));
foreach (var folder in folders)
{
Console.WriteLine($"Folder: {folder.DisplayName}");
}
ItemView view = new ItemView(50);
view.OrderBy.Add(ItemSchema.DateTimeReceived, Microsoft.Exchange.WebServices.Data.SortDirection.Descending);
Folder inbox = Folder.Bind(ewsClient, WellKnownFolderName.Inbox);//Inbox文件夹,不包括子文件夹
PropertySet detailedPropertySet = new PropertySet(BasePropertySet.FirstClassProperties, AppointmentSchema.Body);
findMailResults = ewsClient.FindItems(WellKnownFolderName.Inbox, view);
if (findMailResults != null && findMailResults.Items.Count != 0)
{
ewsClient.LoadPropertiesForItems(from Item item in findMailResults select item, detailedPropertySet);
}
}
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...");
}
return findMailResults;
}
catch (Exception ex)
{
Common comm = new Common();
comm.EmailLog("", ex.Message);
throw;
}
}