Accesso e gestione dei dati di Microsoft 365 con Microsoft Graph
Ottimizza l’accesso e la gestione dei dati Microsoft 365 con il Graph Client di Aspose.Email
Microsoft Graph è un’API REST per accedere ai dati di Microsoft 365. L’implementazione del Graph Client in Aspose.Email per .NET consente l’accesso a Microsoft Graph dalla nostra API. negli esempi seguenti, creeremo un’istanza di MS Graph Client, fornendo il token. Quindi esamineremo i metodi principali per gestire le cartelle, aggiornarle, copiarle e cancellarle. I messaggi, il loro contenuto e gli allegati possono anche essere accessi o modificati con il nostro MS Graph Client. La gestione di categorie, regole, quaderni e sovrascritture è una funzionalità estesa del Microsoft Graph Client di Aspose.Email.
Autenticare e richiedere con IGraphClient usando MSAL in .NET
Per interagire con i servizi Microsoft Graph, dovrai creare un IGraphClient oggetto. Una volta autenticato, questo client ti consente di effettuare varie richieste di servizio. Il GetClient metodo, che crea il IGraphClient, richiede un ITokenProvider implementazione come suo primo parametro. Questo ITokenProvider è responsabile di fornire il token di autenticazione necessario. Per ottenere il token, useremo il Microsoft Authentication Library (MSAL) per .NET.
Ecco come puoi configurare il processo di autenticazione:
Passo 1: Configurare l’autenticazione
I passaggi seguenti ti guideranno su come ottenere un token di autorizzazione:
-
Crea la classe AccessParameters.
Definisci una classe AccessParameters per memorizzare le tue credenziali.
public class AccessParameters
{
public string TenantId { get; init; }
public string ClientId { get; init; }
public string ClientSecret { get; init; }
public string UserId { get; init; }
public Uri Authority => new ($"https://login.microsoftonline.com/{TenantId}");
public string ApiUrl => "https://graph.microsoft.com/.default";
}
-
Aggiungi il Pacchetto MSAL.NET**.
Installa il
Microsoft.Identity.Clientpacchetto NuGet, che contiene i binari MSAL.NET necessari per l’autenticazione. -
Implementa l’interfaccia ITokenProvider.
Crea un
GraphTokenProviderclasse che implementa il ITokenProvider interfaccia. Questa classe utilizzerà la libreria MSAL.NET per acquisire un token di accesso.
using Microsoft.Identity.Client;
using Microsoft.Identity.Web;
using Aspose.Email.Clients;
public class GraphTokenProvider : ITokenProvider
{
private readonly IConfidentialClientApplication _app;
private readonly string[] _scopes;
private string? _token;
public GraphTokenProvider(AccessParameters accessParams)
{
_app = ConfidentialClientApplicationBuilder.Create(accessParams.ClientId)
.WithClientSecret(accessParams.ClientSecret)
.WithAuthority(accessParams.Authority)
.Build();
_app.AddInMemoryTokenCache();
_scopes = new[] { accessParams.ApiUrl };
}
public void Dispose()
{
throw new NotImplementedException();
}
public OAuthToken GetAccessToken()
{
return GetAccessToken(false);
}
public OAuthToken GetAccessToken(bool ignoreExistingToken)
{
if (!ignoreExistingToken && _token != null)
{
return new OAuthToken(_token);
}
_token = GetAccessTokenAsync().GetAwaiter().GetResult();
return new OAuthToken(_token);
}
private async Task<string?> GetAccessTokenAsync()
{
AuthenticationResult? result;
try
{
result = await _app.AcquireTokenForClient(_scopes)
.ExecuteAsync();
Console.WriteLine("Token acquired");
}
catch (MsalServiceException ex) when (ex.Message.Contains("AADSTS70011"))
{
Console.WriteLine("Scope provided is not supported");
result = null;
}
if (result == null) return null;
_token = result.AccessToken;
return result.AccessToken;
}
Passo 2: Crea un’istanza ITokenProvider
Dopo aver definito il GraphTokenProvider classe, puoi creare un’istanza di AccessParameters e usalo per istanziare il GraphTokenProvider.
var accessParams = new AccessParameters()
{
TenantId = "Your Tenant ID",
ClientId = "Your Client ID",
ClientSecret = "Your Client Secret",
UserId = "User's Object ID"
};
var tokenProvider = new GraphTokenProvider(accessParams);
Passo 3: Esegui richieste con IGraphClient
Infine, usa il GraphTokenProvider per creare un autenticato IGraphClient e inizia a fare richieste di servizio.
using var client = GraphClient.GetClient(tokenProvider, accessParams.TenantId);
client.Resource = ResourceType.Users;
client.ResourceId = accessParams.UserId;
Con questi passaggi completati, il tuo IGraphClient è ora pronto a interagire con i servizi Microsoft Graph usando richieste autenticate.
Connessione a endpoint GCC High
Il GraphClient supporta la connessione a endpoint GCC High usando il EndPoint proprietà. Il seguente esempio di codice dimostra come configurare GraphClient per connettersi al endpoint GCC High per elencare cartelle e recuperare messaggi.
client.EndPoint = "https://graph.microsoft.us";
var folders = client.ListFolders();
string folderId = folders.Find(x => x.DisplayName == "Inbox").ItemId;
var msgs = client.ListMessages(folderId);
Gestisci cartelle con IGraphClient
Elenca cartelle
Chiamando ListFolders metodo da MS Graph Client, è possibile ottenere l’elenco delle cartelle. Ogni cartella ha un set di parametri come DisplayName, che può essere letto in FolderInfo tipo.
var folders = client.ListFolders();
foreach (var folder in folders)
{
Console.WriteLine(folder.DisplayName);
}
Aggiorna cartelle
Per creare una cartella con MS Graph Client, usa CreateFolder metodo. Otterrai un FolderInfo oggetto e la possibilità di accedere a DisplayName, ItemId, HasSubFolders e altre proprietà.
var folderInfo = client.CreateFolder("FolderName");
folderInfo.DisplayName = "FolderAnotherName";
client.UpdateFolder(folderInfo);
Copia cartelle
CopyFolder il metodo è il metodo chiave per copiare l’oggetto cartella con MS Graph.
var folderInfo1 = client.CreateFolder("Folder1");
var folderInfo2 = client.CreateFolder("Folder2");
// copy Folder2 to Folder1
client.CopyFolder(folderInfo1.ItemId, folderInfo2.ItemId);
Sposta ed elimina cartelle
Usa MoveFolder il metodo è usato per spostare la cartella, accetta newParentId e itemId. Elimina il metodo è usato per eliminare un metodo per ID.
var folderInfo1 = client.CreateFolder("Folder1");
var folderInfo2 = client.CreateFolder("Folder2");
// move Folder2 to Folder1
client.MoveFolder(folderInfo1.ItemId, folderInfo2.ItemId);
// delete Folder1
client.Delete(folderInfo1.ItemId)
Gestisci messaggi con IGraphClient
MS Graph Client, implementato in Aspose.Email per .NET, fornisce un insieme di metodi per gestire messaggi e allegati:
- Elenca messaggi
- Recupera messaggio
- Crea messaggio
- Invia messaggio
- CopiaMessaggio messaggio
- Sposta messaggio
- CreaAllegato
- RecuperaAllegato
- EliminaAllegato
- ElencaAllegati
Elenca messaggi
var folders = client.ListFolders();
foreach (var folder in folders)
{
if (folder.DisplayName.Equals("Inbox"))
{
// list messages in inbox
var inboxMessages = client.ListMessages(folder.ItemId);
foreach (var messageInfo in inboxMessages)
{
Console.WriteLine(messageInfo.Subject);
}
}
}
Filtra messaggi per data di invio
Il OrderBy il metodo della collezione della libreria consente di recuperare i messaggi con diversi ordini di ordinamento (ascendente e discendente) basati sulla data di invio. Il seguente esempio di codice mostra come ordinare i messaggi per data di invio:
IGraphClient client = GraphClient.GetClient(provider, TenantId);
var builder = new GraphQueryBuilder();
// create orderby messages query 'DESC'
builder.SentDate.OrderBy(false);
var messagePageInfo = client.ListMessages(KnownFolders.Inbox, new PageInfo(10), builder.GetQuery());
var messages = messagePageInfo.Items;
builder.Clear();
// create orderby messages query 'ASC'
builder.SentDate.OrderBy(true);
messagePageInfo = client.ListMessages(KnownFolders.Inbox, new PageInfo(10), builder.GetQuery());
messages = messagePageInfo.Items;
Enumera i messaggi con supporto al paging
L’API consente il paging e il filtraggio dei messaggi quando vengono elencati. È particolarmente utile per caselle di posta con un alto volume di messaggi, poiché risparmia tempo recuperando solo le informazioni di riepilogo necessarie.
L’esempio di codice e i passaggi seguenti dimostrano come recuperare i messaggi dalla cartella Inbox usando le funzionalità di paging e filtraggio.
- Prima, avvia il client.
- Quindi, imposta il numero di elementi da visualizzare per pagina, ad esempio 10.
- Crea un filtro per recuperare solo i messaggi non letti usando il GraphQueryBuilder classe. Il builder.IsRead.Equals(false) imposta la condizione per filtrare i messaggi non letti.
- Chiama il ListMessages metodo sull’oggetto client, specificando la cartella (Inbox) e gli elementi per pagina (PageInfo(itemsPerPage)) come parametri. Passa anche l’oggetto query per applicare il filtro dei messaggi non letti. L’oggetto PageInfo restituito (pageInfo) contiene i messaggi recuperati per la pagina corrente nella proprietà Items.
- Crea un ciclo che continua finché non viene raggiunta l’ultima pagina (pageInfo.LastPage è false). I messaggi recuperati vengono aggiunti all’elenco dei messaggi esistenti usando messages.AddRange(pageInfo.Items).
// reading unread messages with paging
using var client = GraphClient.GetClient(tokenProvider, config.Tenant);
// paging option
var itemsPerPage = 10;
// create unread messages filter
GraphQueryBuilder builder = new GraphQueryBuilder();
builder.IsRead.Equals(false);
var query = builder.GetQuery();
// list messages
var pageInfo = client.ListMessages(KnownFolders.Inbox, new PageInfo(itemsPerPage), query);
var messages = pageInfo.Items;
while (!pageInfo.LastPage)
{
pageInfo = client.ListMessages(KnownFolders.Inbox, pageInfo.NextPage, query);
messages.AddRange(pageInfo.Items);
}
// set messages state as read
foreach (var message in messages)
{
client.SetRead(message.ItemId);
}
Recupera messaggi
var folders = client.ListFolders();
foreach (var folder in folders)
{
if (folder.DisplayName.Equals("Inbox"))
{
// list messages in inbox
var inboxMessages = client.ListMessages(folder.ItemId);
if (inboxMessages.Count > 0)
{
// fetch the first message in inbox
var msg = client.FetchMessage(inboxMessages[0].ItemId);
Console.WriteLine(msg.BodyHtml);
}
}
}
Crea messaggi
var msg = new MapiMessage(OutlookMessageFormat.Unicode)
{
Subject = "My message",
Body = "Hi, it is my message"
};
msg.Recipients.Add("sam@to.com", "Sam", MapiRecipientType.MAPI_TO);
// create message in inbox
client.CreateMessage(KnownFolders.Inbox, msg);
Invia messaggi
// prepare the message
var msg = new MapiMessage(OutlookMessageFormat.Unicode)
{
Subject = "My message",
Body = "Hi, it is my message"
};
msg.Recipients.Add("sam@to.com", "Sam", MapiRecipientType.MAPI_TO);
msg.SetProperty(KnownPropertyList.SenderName, "John");
msg.SetProperty(KnownPropertyList.SentRepresentingEmailAddress, "John@from.com");
// send message
client.Send(msg);
Invia messaggi bozza
// prepare the message
var msg = new MapiMessage(OutlookMessageFormat.Unicode)
{
Subject = "My message",
Body = "Hi, it is my message"
};
msg.Recipients.Add("sam@to.com", "Sam", MapiRecipientType.MAPI_TO);
msg.SetProperty(KnownPropertyList.SenderName, "John");
msg.SetProperty(KnownPropertyList.SentRepresentingEmailAddress, "John@from.com");
// add message to Draft folder
var draftMessage = client.CreateMessage(KnownFolders.Drafts, msg);
// send a draft message
client.Send(draftMessage.ItemId);
Invia messaggi EML
Creare e inviare email è semplice usando l’oggetto MailMessage. Il seguente esempio di codice dimostra come creare e inviare un messaggio email usando Graph API:
// prepare the message
var eml = new MailMessage
{
From = "from@domain.com",
To = "to1@domain.com, to2@domain.com",
Subject = "New message",
HtmlBody = "<html><body>This is the HTML body</body></html>"
};
// send the message
graphClient.Send(eml);
graphClient.Create(KnownFolders.Inbox, eml);
Copia messaggi
// copy message to Inbox folder
var copiedMsg = client.CopyMessage(KnownFolders.Inbox, msg.ItemId);
Sposta messaggi
// move message to Inbox folder
var movedMsg = client.MoveMessage(KnownFolders.Inbox, msg.ItemId);
Gestisci Allegati
// create an attachment
var attachment = new MapiAttachment();
attachment.SetProperty(KnownPropertyList.DisplayName, "My Attachment");
attachment.SetProperty(KnownPropertyList.AttachDataBinary, new byte[1024]);
// add an attachment to message
var createdAttachment = client.CreateAttachment(messageInfo.ItemId, attachment);
// fetch a message attachment
var fetchedAttachment = client.FetchAttachment(createdAttachment.ItemId);
// delete a message attachment
client.DeleteAttachment(createdAttachment.ItemId);
// list the message attachments
var attachments = client.ListAttachments(messageInfo.ItemId);
Gestisci elementi Outlook con Graph Client
Gestisci eventi del calendario
Aspose.Email fornisce API per accedere, gestire e interagire con gli eventi del calendario. A tal fine, offre i seguenti metodi in IGraphClient interfaccia:
- ListCalendars() - Recupera una collezione di informazioni sui calendari.
- ListCalendarItems(string id) - Recupera una collezione di elementi calendario associati all’ID del calendario specificato.
- FetchCalendarItem(string id) - Recupera un elemento calendario specifico in base all’ID fornito.
- CreateCalendarItem(string calId, MapiCalendar mapiCalendar) - Crea un nuovo elemento calendario nel calendario specificato.
- UpdateCalendarItem(MapiCalendar mapiCalendar) - Aggiorna un elemento calendario esistente.
- UpdateCalendarItem(MapiCalendar mapiCalendar, UpdateSettings updateSettings) - Aggiorna un elemento calendario esistente con le impostazioni di aggiornamento specificate.
Il seguente esempio di codice dimostra come interagire con gli eventi del calendario in un client Microsoft Graph API usando i metodi forniti da Aspose.Email:
// List Calendars
CalendarInfoCollection calendars = graphClient.ListCalendars();
// List Calendar Items
MapiCalendarCollection calendarItems = graphClient.ListCalendarItems("calendarId");
// Fetch Calendar Item
MapiCalendar calendarItem = graphClient.FetchCalendarItem("calendarItemId");
// Create Calendar Item
MapiCalendar newCalendarItem = new MapiCalendar(
location: "Conference Room",
summary: "Team Meeting",
description: "Discuss project status and updates.",
startDate: startDate,
endDate: endDate
);
MapiCalendar createdCalendarItem = graphClient.CreateCalendarItem("calendarId", newCalendarItem);
// Update Calendar Item
createdCalendarItem.Location = "Zoom Meeting";
MapiCalendar updatedCalendarItem = graphClient.UpdateCalendarItem(createdCalendarItem);
Gestisci categorie
Per gestire le categorie con MS Graph di Aspose.Email per .NET, utilizzare i seguenti metodi:
// create a custom category with Orange color
var category = client.CreateCategory("My custom category", CategoryPreset.Preset1);
// fetch a category
var fetchedCategory = client.FetchCategory(category.Id);
// update category (change color to brown)
fetchedCategory.Preset = CategoryPreset.Preset2;
var updatedCategory = client.UpdateCategory(fetchedCategory);
// list available categories
var categories = client.ListCategories();
foreach (var cat in categories)
{
Console.WriteLine(cat.DisplayName);
}
// delete a category
client.Delete(fetchedCategory.Id);
Gestisci contatti
Aspose.Email fornisce API per accedere, gestire e interagire con gli elementi contatto. A tal fine, offre i seguenti metodi in IGraphClient interfaccia:
- ListContacts(string id) - Recupera una collezione di contatti MAPI associati all’ID della cartella specificata.
- FetchContact(string id) - Recupera un contatto specifico in base all’ID dell’elemento fornito.
- CreateContact(string folderId, MapiContact contact) - Crea un nuovo contatto nella cartella specificata.
- UpdateContact(MapiContact contact) - Aggiorna un contatto esistente.
Il seguente esempio di codice dimostra come interagire con i contatti in un client Microsoft Graph API utilizzando i metodi forniti da Aspose.Email:
// List Contacts
MapiContactCollection contacts = graphClient.ListContacts("contactFolderId");
// Fetch Contact
MapiContact contact = graphClient.FetchContact("contactId");
// Create Contact
MapiContact newContact = new MapiContact("Jane Smith", "jane.smith@example.com", "XYZ Corporation", "777-888-999");
MapiContact createdContact = graphClient.CreateContact("contactFolderId", newContact);
// Update Contact
createdContact.Telephones.PrimaryTelephoneNumber = "888-888-999";
MapiContact updatedContact = graphClient.UpdateContact(createdContact);
Gestisci sovrascritture
Per gestire le sovrascritture con MS Graph di Aspose.Email per .NET, utilizzare i seguenti metodi:
// Create an user's override
var userOverride = client.CreateOrUpdateOverride
(new MailAddress("JohnBrown@someorg.com", "JohnBrown"), ClassificationType.Focused);
// list the overrides
var overrides = client.ListOverrides();
// update override
userOverride.Sender.DisplayName = "John Brown";
var updatedOverride = client.UpdateOverride(userOverride);
// delete override
client.Delete(updatedOverride.Id);
Gestisci regole
Per gestire le regole con MS Graph di Aspose.Email per .NET, utilizzare i seguenti metodi:
// Create a rule
var rule = PrepareRule("user@someorg.com", "User");
var createdRule = client.CreateRule(rule);
// List all rules defined for Inbox
var rules = client.ListRules();
// Fetch a rule
var fetchedRule = client.FetchRule(createdRule.RuleId);
// Update a rule
fetchedRule.DisplayName = "Renamed rule";
fetchedRule.IsEnabled = false;
var updatedRule = client.UpdateRule(createdRule);
// Delete a rule
client.Delete(updatedRule.RuleId);
InboxRule PrepareRule(string email, string displayName)
{
var rule = new InboxRule()
{
DisplayName = "My rule",
Priority = 1,
IsEnabled = true,
Conditions = new RulePredicates(),
Actions = new RuleActions()
};
rule.Conditions.ContainsSenderStrings = new StringCollection { displayName };
rule.Actions.ForwardToRecipients = new MailAddressCollection
{ new MailAddress(email, displayName, true) };
rule.Actions.StopProcessingRules = true;
return rule;
}
Gestisci blocchi note
Per gestire i blocchi note con MS Graph di Aspose.Email per .NET, utilizzare i seguenti metodi:
// create a OneNote notebook
var newNotebook = new Notebook()
{
DisplayName = "My Notebook"
};
var createdNotebook = client.CreateNotebook(newNotebook);
// fetch a notebook
var fetchedNotebook = client.FetchNotebook(createdNotebook.Id);
// list the notebooks
var notebooks = client.ListNotebooks();
Gestione delle attività in Microsoft Graph
Aspose.Email fornisce agli sviluppatori API per accedere, gestire e interagire con le attività e le liste di attività degli utenti usando i seguenti metodi di IGraphClient interfaccia:
- ListTaskLists() - Recupera una raccolta di informazioni sugli elenchi attività.
- GetTaskList(string id) - Recupera un elenco attività specifico in base all’ID fornito.
- DeleteTaskList(string id) - Elimina la lista di attività specificata. -ListTasks(string id) - Recupera una collezione di attività associate all’ID della lista di attività specificata.
- FetchTask(string id) - Recupera un’attività specifica in base all’ID fornito.
- CreateTask(MapiTask task, string taskListUri) - Crea una nuova attività nella lista di attività specificata.
- UpdateTask(MapiTask task) - Aggiorna un’attività esistente con le informazioni fornite.
- UpdateTask(MapiTask task, UpdateSettings updateSettings) - Aggiorna un’attività esistente con le impostazioni di aggiornamento specificate.
Il seguente esempio di codice dimostra come gestire le liste di attività:
// List Task Lists
var taskLists = graphClient.ListTaskLists();
foreach (var tList in taskLists)
{
Console.WriteLine($"Task List: {tList.DisplayName}");
}
// Get Task List
var taskList = graphClient.GetTaskList("taskListId");
// Delete Task List
graphClient.DeleteTaskList("taskListId");
Il seguente esempio di codice dimostra come gestire le attività:
// List Tasks in a Task List
MapiTaskCollection tasks = graphClient.ListTasks("taskListId");
// Fetch Task
MapiTask task = graphClient.FetchTask("taskId");
// Create Task
var newTask = new MapiTask
{
Subject = "New Task",
DueDate = new DateTime(2023, 12, 31),
Status = MapiTaskStatus.NotStarted
};
MapiTask createdTask = graphClient.CreateTask(newTask, "taskListUri");
// Update Task
createdTask.Subject = "Updated Task Subject";
MapiTask updatedTask = graphClient.UpdateTask(createdTask);
// Update Task with UpdateSettings
var updateSettings = new UpdateSettings { SkipAttachments = true };
MapiTask updatedTaskWithSettings = graphClient.UpdateTask(createdTask, updateSettings);