MailKit 可以用来在 azure 上使用 graph 发送电子邮件吗

问题描述 投票:0回答:1

过去,azure(outlook 365)允许用户使用 SMTP 从应用程序发送电子邮件,但在过去的一年里,这种情况发生了变化,Micrsoft.Client.Identity 授予的令牌不能在 MailKit SmtpClient 中使用,除非用户的 Outlook365 帐户删除默认值天蓝色的安全。我不确定他们为什么这样做,但我们一直在寻找一种通过我们的应用程序发送电子邮件的方法。

我们发现了关于使用 Microsoft graph 发送电子邮件的问题文章,并且这有效。在本文中,代码设置了一条 json 电子邮件消息。我想知道我们是否可以使用 MailKit 设置电子邮件并使用 MailKit 方法发送,或者我们是否只需要将使用 MailKit 创建的电子邮件序列化为 json,然后像文章那样执行 PostAsync。

azure email mailkit
1个回答
0
投票

是的,您可以使用 Malkit 来发送邮件,如下所示:

创建 Azure AD 应用程序并分配以下 API 权限:

enter image description here

授予用户访问权限:

Add-MailboxPermission -Identity "[email protected]" -User ServicePrincipalID -AccessRights FullAccess

例如,我使用客户端凭证流程通过以下参数生成令牌:

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

enter image description here

通过使用上述令牌,您可以发送如下邮件:

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

但建议使用 Microsoft Graph API 发送邮件进行 OAuth2 身份验证。请参考我的SO Thread

参考资料:

使用 OAuth 验证 IMAP、POP 或 SMTP 连接 |微软

MailKit/ExchangeOAuth2.md at master · jstedfast/MailKit · GitHub by jstedfast

© www.soinside.com 2019 - 2024. All rights reserved.