前面写了PHP使用Microsoft Graph API发送邮件的教程,但批量发送邮件这种耗时操作使用PHP语言来做还是有点不大合适,因此有了本系列教程C#使用Microsoft Graph API发送邮件。本系列教程将结合wordpress用户系统使用Microsoft Graph API群发邮件,先来看看第一篇获得Microsoft Graph授权。
前期准备
visual studio 2019(低版本无法使用MSAL)
创建一个Microsoft Graph应用,地址:https://portal.azure.com/。如果有不清楚的地方请看之前的文章Microsoft Graph开放接口学习——获得授权token
应用配置如下权限,不然无法使用发送邮件功能。
应用类型不要选WEB,选桌面应用程序。
回调地址写:https://login.microsoftonline.com/common/oauth2/nativeclient
编写程序
安装MSAL.NET
使用vs2019创建一个Windows桌面应用程序,再点击菜单栏的工具——NuGet包管理器——程序包管理器控制台,在打开的控制台中输入如下命令安装Microsoft Graph SDK包。
Install-Package Microsoft.Identity.Client -IncludePrerelease
MSAL (Microsoft.Identity.Client) 是一个库,用于用户登录和请求令牌,此类令牌用于访问受 Microsoft 标识平台保护的 API。
初始化MSAL
添加引用
using Microsoft.Identity.Client;
声明全局变量
public static IPublicClientApplication PublicClientApp;
在主窗体初始化事件中写下如下代码:
PublicClientApp= PublicClientApplicationBuilder.Create(ClientId) .WithRedirectUri("https://login.microsoftonline.com/common/oauth2/nativeclient") .WithAuthority(AzureCloudInstance.AzurePublic, Tenant) .Build();
其中Tenant是静态值,我们这里值是common
。ClientId是我们创建的应用id。为了方便,可以将这些变量单独声明一下。
string graphAPIEndpoint = "https://graph.microsoft.com/v1.0/me"; private static string ClientId = "exxxxxxxxxxxxxx"; private static string Tenant = "common"; private static string[] scopes = { "user.read", "mail.read", "mail.send" };//权限
获取授权
AuthenticationResult authResult = null; var app = PublicClientApp; ResultText.Text = string.Empty; TokenInfoText.Text = string.Empty; var accounts = await app.GetAccountsAsync(); var firstAccount = accounts.FirstOrDefault(); try { authResult = await app.AcquireTokenSilent(scopes, firstAccount) .ExecuteAsync(); } catch (MsalUiRequiredException ex) { // A MsalUiRequiredException happened on AcquireTokenSilent. // This indicates you need to call AcquireTokenInteractive to acquire a token System.Diagnostics.Debug.WriteLine($"MsalUiRequiredException: {ex.Message}"); try { authResult = await app.AcquireTokenInteractive(scopes) .WithAccount(accounts.FirstOrDefault()) .WithParentActivityOrWindow(this) .WithPrompt(Prompt.SelectAccount) .ExecuteAsync(); } catch (MsalException msalex) { ResultText.Text = $"Error Acquiring Token:{System.Environment.NewLine}{msalex}"; } } catch (Exception ex) { ResultText.Text = $"Error Acquiring Token Silently:{System.Environment.NewLine}{ex}"; return; } if (authResult != null) { ResultText.Text = await GetHttpContentWithToken(graphAPIEndpoint, authResult.AccessToken); DisplayBasicTokenInfo(authResult); }
涉及到的其它方法如下:
/// <summary> /// Perform an HTTP GET request to a URL using an HTTP Authorization header /// </summary> /// <param name="url">The URL</param> /// <param name="token">The token</param> /// <returns>String containing the results of the GET operation</returns> public async Task<string> GetHttpContentWithToken(string url, string token) { var httpClient = new System.Net.Http.HttpClient(); System.Net.Http.HttpResponseMessage response; try { var request = new System.Net.Http.HttpRequestMessage(System.Net.Http.HttpMethod.Get, url); //Add the token in Authorization header request.Headers.Authorization = new System.Net.Http.Headers.AuthenticationHeaderValue("Bearer", token); response = await httpClient.SendAsync(request); var content = await response.Content.ReadAsStringAsync(); return content; } catch (Exception ex) { return ex.ToString(); } } /// <summary> /// Display basic information contained in the token /// </summary> private void DisplayBasicTokenInfo(AuthenticationResult authResult) { TokenInfoText.Text = ""; if (authResult != null) { TokenInfoText.Text += $"Username: {authResult.Account.Username}" + Environment.NewLine; TokenInfoText.Text += $"Token: {authResult.AccessToken}" + Environment.NewLine; TokenInfoText.Text += $"Token Expires: {authResult.ExpiresOn.ToLocalTime()}" + Environment.NewLine; } }
点击按钮后会要求用户登录账号,并授权。
授权完成后会返回用户授权令牌给程序。
使用这个令牌我们就可以开始接下来的发送邮件操作了。
原创文章,作者:奋斗,如若转载,请注明出处:https://blog.ytso.com/241341.html