【问题标题】:Using Oauth2 to send email via Office365 C#使用 Oauth2 通过 Office365 C# 发送电子邮件
【发布时间】:2021-02-24 14:53:04
【问题描述】:

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

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

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

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

【问题讨论】:

    标签: c# email oauth smtp office365


    【解决方案1】:

    您可以通过使用 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

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

    【讨论】:

    【解决方案2】:

    可以在此处找到使用 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);
    }
    

    【讨论】:

      猜你喜欢
      • 2020-02-06
      • 2017-10-12
      • 2012-10-01
      • 2022-08-14
      • 2020-05-01
      • 1970-01-01
      • 2021-06-23
      • 1970-01-01
      相关资源
      最近更新 更多