繁体   English   中英

使用 Oauth2 通过 Office365 C# 发送 email

[英]Using Oauth2 to send email via Office365 C#

我正在尝试使用 Oauth2 和 Office 365 帐户在 c# 中发送 email 。

目前我能够获得令牌,但不确定如何使用该令牌并发送 email。

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

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

您可以通过使用 OAuth 令牌创建 OAuthCredentials 对象,然后在 ExchangeService 对象上设置凭据和终结点来使用 EWS 托管 api。 然后,您可以使用 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

go forward 方法是 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);
}

下午好,过得如何? 您是否能够在 outlook 365 中使用 oauth 发送电子邮件? 你能把代码分享给我吗? 我不明白。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM