簡體   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