使用 Oauth2 通过 Office365 C# 发送电子邮件

Using Oauth2 to send email via Office365 C#

我正在尝试使用带有 Office 365 帐户的 Oauth2 在 c# 中发送电子邮件。

目前我可以获得令牌,但不确定如何使用该令牌并发送电子邮件。

System.Net.Mail 不支持 OAuth 或 OAuth2。

我看过 Mailkit,但示例都是针对 google 邮件的,没有看到针对 Office 365 的示例,所以我不确定从哪里开始。

您可以使用 EWS 托管 api,方法是使用 OAuth 令牌创建 OAuthCredentials 对象,然后在 ExchangeService 对象上设置凭据和端点。然后您可以使用 ExchangeService 对象来创建和发送电子邮件。

var credentials = new OAuthCredentials(token);
var ews = new ExchangeService();
ews.Credentials = credentials;
ews.Url = endpointUrl;

var email = new EmailMessage(ews);
...

email.Send();

https://docs.microsoft.com/en-us/exchange/client-developer/web-service-reference/ews-managed-api-reference-for-exchange

前进的方法是 Microsoft Graph,但我不太熟悉它。 https://docs.microsoft.com/en-us/graph/api/resources/mail-api-overview?view=graph-rest-1.0

可在此处找到使用 MailKit 和 Office365 进行 OAuth2 身份验证的文档:https://github.com/jstedfast/MailKit/blob/master/ExchangeOAuth2.md

var options = new PublicClientApplicationOptions {
    ClientId = "Application (client) ID",
    TenantId = "Directory (tenant) ID",
    RedirectUri = "https://login.microsoftonline.com/common/oauth2/nativeclient"
};
 
var publicClientApplication = PublicClientApplicationBuilder
    .CreateWithApplicationOptions (options)
    .Build ();
 
var scopes = new string[] {
    "email",
    "offline_access",
    "https://outlook.office.com/IMAP.AccessAsUser.All", // Only needed for IMAP
    //"https://outlook.office.com/POP.AccessAsUser.All",  // Only needed for POP
    //"https://outlook.office.com/SMTP.Send", // Only needed for SMTP
};

var authToken = await publicClientApplication.AcquireTokenInteractive (scopes).ExecuteAsync ();

var oauth2 = new SaslMechanismOAuth2 (authToken.Account.Username, authToken.AccessToken);

using (var client = new ImapClient ()) {
    await client.ConnectAsync ("outlook.office365.com", 993, SecureSocketOptions.SslOnConnect);
    await client.AuthenticateAsync (oauth2);
    await client.DisconnectAsync (true);
}