Microsoft Graph を使用した Microsoft 365 データのアクセスと管理

Aspose.Email Graph Client で Microsoft 365 データのアクセスと管理を最適化

Microsoft Graph Microsoft Graph は Microsoft 365 データにアクセスするための REST API です。Aspose.Email for .NET の Graph Client 実装により、当社の API から Microsoft Graph にアクセスできます。以下の例では、トークンを提供して MS Graph Client のインスタンスを作成します。その後、フォルダーの管理、更新、コピー、削除などの主要メソッドを検証します。メッセージ、その内容および添付ファイルも、当社の MS Graph Client を使用してアクセスまたは変更できます。カテゴリ、ルール、ノートブック、オーバーライドの管理は、Aspose.Email の Microsoft Graph Client による拡張機能です。

.NET で MSAL を使用して IGraphClient で認証およびリクエスト

Microsoft Graph サービスとやり取りするには、以下を作成する必要があります。 IGraphClient オブジェクトです。認証が完了すると、このクライアントでさまざまなサービスリクエストを実行できます。 GetClient メソッドで、これにより IGraphClient、が必要です ITokenProvider 実装を最初のパラメータとして渡します。この ITokenProvider は必要な認証トークンを提供します。トークンを取得するには、次を使用します。 Microsoft Authentication Library(MSAL) .NET 用。

認証プロセスの設定方法は次のとおりです:

ステップ 1: 認証の設定

以下の手順で認可トークンの取得方法をご案内します:

  1. AccessParameters クラスを作成する。

    資格情報を保存するための AccessParameters クラスを定義します。

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";
}
  1. 追加 MSAL.NET パッケージ**.

    インストールする Microsoft.Identity.Client 認証に必要な MSAL.NET バイナリを含む NuGet パッケージです。

  2. ITokenProvider インターフェイスを実装する。

    作成する GraphTokenProvider 実装するクラス ITokenProvider インターフェイス。このクラスは MSAL.NET ライブラリを使用してアクセストークンを取得します。

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;
    }

ステップ 2: ITokenProvider インスタンスの作成

定義した後、 GraphTokenProvider クラス、インスタンスを作成できます AccessParameters そしてそれを使用してインスタンス化します 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);

ステップ 3: IGraphClient でリクエストを行う

最後に、次を使用します GraphTokenProvider 認証された…を作成するために IGraphClient そしてサービスリクエストを開始できます。

using var client = GraphClient.GetClient(tokenProvider, accessParams.TenantId);

client.Resource = ResourceType.Users;
client.ResourceId = accessParams.UserId;

これらの手順が完了すると、あなたの IGraphClient は認証済みリクエストを使用して Microsoft Graph サービスとやり取りする準備が整いました。

GCC High エンドポイントへの接続

この GraphClient GCC High エンドポイントへの接続は、次を使用してサポートされます EndPoint プロパティです。以下のコードサンプルは、フォルダーの一覧取得とメッセージ取得のために GCC High エンドポイントに接続するよう GraphClient を構成する方法を示しています。

client.EndPoint = "https://graph.microsoft.us";

var folders = client.ListFolders();
string folderId = folders.Find(x => x.DisplayName == "Inbox").ItemId;
var msgs = client.ListMessages(folderId);

IGraphClient でフォルダーを管理

フォルダー一覧

呼び出すことで ListFolders MS Graph Client のメソッドを使用すると、フォルダーのリストを取得できます。各フォルダーには DisplayName などのパラメータセットがあり、これらは FolderInfo タイプです。

var folders = client.ListFolders();

foreach (var folder in folders)
{
    Console.WriteLine(folder.DisplayName);
}

フォルダーの更新

MS Graph Client でフォルダーを作成するには、次を使用します CreateFolder メソッドです。取得できるのは FolderInfo オブジェクトと、DisplayName、ItemId、HasSubFolders などのプロパティにアクセスできる可能性。

var folderInfo = client.CreateFolder("FolderName");
folderInfo.DisplayName = "FolderAnotherName";
client.UpdateFolder(folderInfo);

フォルダーのコピー

CopyFolder このメソッドは MS Graph でフォルダーオブジェクトをコピーする主要なメソッドです。

var folderInfo1 = client.CreateFolder("Folder1");
var folderInfo2 = client.CreateFolder("Folder2");
    
// copy Folder2 to Folder1
client.CopyFolder(folderInfo1.ItemId, folderInfo2.ItemId);

フォルダーの移動と削除

使用する MoveFolder このメソッドはフォルダーを移動するために使用され、newParentId と itemId を受け取ります。 削除 このメソッドは 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)

IGraphClient でメッセージを管理

.NET 用 Aspose.Email で実装された MS Graph Client は、メッセージと添付ファイルを管理するための一連のメソッドを提供します。

メッセージ一覧

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);
        }
    }
}

送信日付でメッセージをフィルタ

この OrderBy ライブラリコレクションのメソッドにより、送信日付に基づいて異なるソート順(昇順・降順)でメッセージを取得できます。以下のコードサンプルは、送信日付でメッセージを並べ替える方法を示しています。

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;

ページング対応でメッセージを列挙

API はメッセージの一覧取得時にページングとフィルタリングを可能にします。大量のメッセージがあるメールボックスで特に有用で、必要な要約情報のみを取得することで時間を節約できます。

以下のコードサンプルと手順は、ページングとフィルタリング機能を使用して受信トレイフォルダーからメッセージを取得する方法を示しています。

  1. まず、クライアントを初期化します。
  2. 次に、ページあたりに表示するアイテム数を設定します。例: 10。
  3. 未読メッセージだけを取得するフィルタを作成します。 GraphQueryBuilder クラスです。builder.IsRead.Equals(false) は未読メッセージをフィルタリングする条件を設定しています。
  4. 呼び出す ListMessages クライアントオブジェクトのメソッドで、フォルダー(Inbox)とページあたりのアイテム数(PageInfo(itemsPerPage))をパラメータとして指定します。また、未読メッセージフィルタを適用するためにクエリオブジェクトも渡します。返された PageInfo オブジェクト(pageInfo)には、現在のページの取得メッセージが Items プロパティに含まれます。
  5. 最後のページに達するまで(pageInfo.LastPage が false になるまで)ループを作成します。取得したメッセージは 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);
}

メッセージの取得

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);
        }
        
    }
}

メッセージの作成

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);

メッセージの送信

// 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);

下書きメッセージの送信

// 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);

EML メッセージの送信

MailMessage オブジェクトを使用すれば、メールの作成と送信が簡単です。以下のコードサンプルは、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);

メッセージのコピー


// copy message to Inbox folder
var copiedMsg = client.CopyMessage(KnownFolders.Inbox, msg.ItemId);

メッセージの移動

// move message to Inbox folder
var movedMsg = client.MoveMessage(KnownFolders.Inbox, msg.ItemId);

添付ファイルの管理


// 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);   

Graph クライアントで Outlook アイテムを管理

カレンダーイベントの管理

Aspose.Email は、カレンダーイベントへのアクセス、管理、操作のための API を提供します。この目的のために、次のメソッドを提供します。 IGraphClient インターフェイス:

  • ListCalendars() - カレンダー情報のコレクションを取得します。
  • ListCalendarItems(string id) - 指定されたカレンダー ID に関連付けられたカレンダー項目のコレクションを取得します。
  • FetchCalendarItem(string id) - 指定された ID に基づいて特定のカレンダー項目を取得します。
  • CreateCalendarItem(string calId, MapiCalendar mapiCalendar) - 指定されたカレンダーに新しいカレンダー項目を作成します。
  • UpdateCalendarItem(MapiCalendar mapiCalendar) - 既存のカレンダー項目を更新します。
  • UpdateCalendarItem(MapiCalendar mapiCalendar, UpdateSettings updateSettings) - 指定された更新設定で既存のカレンダー項目を更新します。

以下のコードサンプルは、Aspose.Email が提供するメソッドを使用して Microsoft Graph API クライアントでカレンダーイベントとやり取りする方法を示しています。


// 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);

カテゴリの管理

.NET 用 Aspose.Email の MS Graph でカテゴリを管理するには、次のメソッドを使用します。

// 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);

連絡先の管理

Aspose.Email は、連絡先アイテムへのアクセス、管理、操作のための API を提供します。この目的のために、次のメソッドを提供します。 IGraphClient インターフェイス:

  • ListContacts(string id) - 指定されたフォルダー ID に関連付けられた MAPI 連絡先のコレクションを取得します。
  • FetchContact(string id) - 指定されたアイテム ID に基づいて特定の連絡先を取得します。
  • CreateContact(string folderId, MapiContact contact) - 指定されたフォルダーに新しい連絡先を作成します。
  • UpdateContact(MapiContact contact) - 既存の連絡先を更新します。

以下のコードサンプルは、Aspose.Email が提供するメソッドを使用して Microsoft Graph API クライアントで連絡先とやり取りする方法を示しています。

// 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);

オーバーライドの管理

.NET 用 Aspose.Email の MS Graph でオーバーライドを管理するには、次のメソッドを使用します。

// 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);

ルールの管理

.NET 用 Aspose.Email の MS Graph でルールを管理するには、次のメソッドを使用します。

// 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;
}

ノートブックの管理

.NET 用 Aspose.Email の MS Graph でノートブックを管理するには、次のメソッドを使用します。

// 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();

Microsoft Graph におけるタスク管理

Aspose.Email は、以下のメソッドを使用してユーザーのタスクおよびタスクリストにアクセス、管理、操作するための API を提供します。 IGraphClient インターフェイス:

以下のコードサンプルは、タスクリストの管理方法を示します。

// 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");

以下のコードサンプルは、タスクの管理方法を示します。

// 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);