C# 來取得365 Outlook相關資訊,使用 Microsoft.Graph 讀取 帳號、帳號管理者、行事曆、行事曆事件等資訊

 在學習此操作之前先準備了解一下相關資訊及學習資源


線上API範本
https://developer.microsoft.com/en-us/graph/graph-explorer

線上操作文件
https://learn.microsoft.com/en-us/graph/overview?view=graph-rest-1.0
https://learn.microsoft.com/zh-cn/graph/overview



基本上我們必須先準備好下列4個數據資訊
string clientId = "應用程式 (用戶端) 識別碼";
string authority = "目錄 (租用戶) 識別碼";
string account = "Office 365 使用者的電子郵件信箱";
string password = "Office 365 使用者的密碼";

clientId = "應用程式 (用戶端) 識別碼"


authority = "目錄 (租用戶) 識別碼"


操作權限的開啟

權限開放



/// <summary>
/// 取得授權
/// </summary>
/// <returns></returns>
static async Task<AuthenticationResult> GetAuth()
{
string[] scopes = new string[] { "user.read", "Calendars.ReadBasic" };
IPublicClientApplication app;
app = PublicClientApplicationBuilder.Create(clientId)
.WithAuthority($"https://login.microsoftonline.com/{authority}")
.Build();

AuthenticationResult result = null;
try
{
// 使用使用者的帳號與密碼憑證,來獲取存取權杖
result = await app.AcquireTokenByUsernamePassword(scopes, account, password).ExecuteAsync();


Console.WriteLine($"Login Account : {result.Account.Username}");
Console.WriteLine($"Access Token : {result.AccessToken}");
Console.WriteLine($"Auth Scope :");
foreach (var item in result.Scopes)
{
Console.WriteLine($"  --  {item}");
}

}
catch (MsalException ex)
{
Console.WriteLine(ex.Message);
}
return result;
}


/// <summary>
/// 取得所有使用者資訊
/// </summary>
/// <returns></returns>
static async Task GetUsers()
{
// 取得權杖
var result = await GetAuth();

// 建構Graph物件
var graphClient = new GraphServiceClient(new DelegateAuthenticationProvider((requestMessage) =>
{
requestMessage
.Headers
.Authorization = new AuthenticationHeaderValue("bearer", result.AccessToken);
return Task.FromResult(0);
}));

// 取得使用者清單資訊
var Users = await graphClient.Users.Request().GetAsync();
foreach (var user in Users)
{
Console.WriteLine($"UserName:{user.DisplayName} - {user.Mail}");
try
{
// 取得該使用者所指定的管理者(組織上級)
var Mang = await graphClient.Users[user.Id].Manager.Request().GetAsync();
Console.WriteLine($" -- Manager:{((Microsoft.Graph.User)Mang).DisplayName} - {((Microsoft.Graph.User)Mang).Mail}");
}
catch
{

}
}
}

留言

這個網誌中的熱門文章

delivery note和delivery order的區別和翻譯

Eclipse 3.6.1 Helios 中文化方法

牙技專業英文--技工篇