如何使用 oauth2 验证 SMTP 连接以在 C# 中发送邮件?
我使用 MSal 库生成了令牌
我有这些参数
客户端ID, 客户秘密, 权限:https://login.microsoftonline.com/TenantId 和 范围:https://graph.microsoft.com/.default
我不知道这些设置是否是能够使用 oauth2 通过 SMTP 发送电子邮件(office 365)的正确设置。该应用程序已在 Azure Ad(Microsoft 条目 ID)上注册。在这一个上,我有活跃的 Microsoft Graph 和 Microsoft Exchange Online
如果不可能,有解决方法 预先感谢。
创建 Azure AD 应用程序并授予 Office 365 Exchange Online API 权限:
通过使用以下参数来利用客户端凭证流程:
https://login.microsoftonline.com/TenantID/oauth2/v2.0/token
client_id:ClientID
client_secret:ClientSecret
grant_type:client_credentials
scope:https://outlook.office.com/.default
使用以下代码来验证使用 oauth 发送邮件的 SMTP 连接:
var confidentialClientApplication = ConfidentialClientApplicationBuilder.Create (clientId)
.WithAuthority ($"https://login.microsoftonline.com/{tenantId}/v2.0")
.WithCertificate (certificate) // or .WithClientSecret (clientSecret)
.Build ();
var scopes = new string[] {
// For IMAP and POP3, use the following scope
"https://ps.outlook.com/.default"
// For SMTP, use the following scope
// "https://outlook.office365.com/.default"
};
var authToken = await confidentialClientApplication.AcquireTokenForClient (scopes).ExecuteAsync ();
var oauth2 = new SaslMechanismOAuth2 (accountEmailAddress, authToken.AccessToken);
using (var client = new ImapClient ()) {
await client.ConnectAsync ("outlook.office365.com", 993, SecureSocketOptions.SslOnConnect);
await client.AuthenticateAsync (oauth2);
await client.DisconnectAsync (true);
}
并向用户添加授予访问权限:
Add-MailboxPermission -Identity "[email protected]" -User ServicePrincipalID -AccessRights FullAccess
参考资料:
MailKit/ExchangeOAuth2.md at master · jstedfast/MailKit · GitHub by jstedfast