使用Oauth2通过C#发送Office365电子邮件

7

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

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

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

我看到了Mailkit,但是示例都是针对Google Mail的,并没有看到适用于Office 365的示例,所以我不太确定从哪里开始。

3个回答

6

有关在 Office365 中使用 MailKit 进行 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);
}

“Mailkit”是否不支持与“ConfidentialClient”一起使用Oauth? - hiFI
MailKit没有这样的限制。如果CredentialClient不起作用,那么这就是服务器的限制。 - jstedfast
你正在编写一个ASP.NET应用程序吗? - jstedfast
是的。这是我的 .Net 控制台应用程序。在 AppRegistration 更改后,我现在正在获取令牌。现在无法获取 authToke.Account.UserName。我正在遵循您的示例代码。.new SaslMechanismOAuthBearer(authToken.Account.UserName, authToken.AccessToken); - Mit Jacob

3

使用this设置应用程序。

   namespace SendEmailWithMicrosoftGraph
    {
        class Program
        {
            static async Task Main(string[] args)
            {
                // Set up the Microsoft Graph API endpoint and version
                string graphApiEndpoint = "https://graph.microsoft.com/v1.0";
    
                // Set up the client application ID and secret
                string clientId = "<clientId>";
                string clientSecret = "<clientSecret>";
                string tenantId = "<tenentId>";
    
                // Set up the user's email address and message content
                string userEmail = "<userEmail>";
                string messageSubject = "Test email";
                string messageBody = "This is a test email sent via Microsoft Graph";
    
                // Set up the authentication context and acquire a token
                var authBuilder = ConfidentialClientApplicationBuilder.Create(clientId)
                    .WithAuthority($"https://login.microsoftonline.com/{tenantId}/v2.0")
                    .WithClientSecret(clientSecret)
                    .Build();
    
                var authResult = await authBuilder.AcquireTokenForClient(new[] { "https://graph.microsoft.com/.default" })
                    .ExecuteAsync();
    
                // Set up the HTTP client and add the access token to the authorization header
                var httpClient = new HttpClient();
                httpClient.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", authResult.AccessToken);
    
                // Set up the email message
                var emailMessage = new
                {
                    message = new
                    {
                        subject = messageSubject,
                        body = new
                        {
                            contentType = "Text",
                            content = messageBody
                        },
                        toRecipients = new[]
                        {
                            new
                            {
                                emailAddress = new
                                {
                                    address = userEmail
                                }
                            }
                        }
                    }
                };
    
                // Convert the email message to a JSON string and send the email via Microsoft Graph
                var jsonMessage = JsonConvert.SerializeObject(emailMessage);
                var response = await httpClient.PostAsync($"{graphApiEndpoint}/users/{userEmail}/sendMail", new StringContent(jsonMessage, System.Text.Encoding.UTF8, "application/json"));
    
                if (response.IsSuccessStatusCode)
                {
                    Console.WriteLine("Email sent successfully.");
                }
                else
                {
                    Console.WriteLine("Failed to send email. Status code: " + response.StatusCode);
                }
            }
        }
    }

2

您可以使用 EWS 管理的 API,通过创建一个 OAuthCredentials 对象并使用 OAuth 令牌设置凭据和终结点在 ExchangeService 对象上。然后您可以使用 ExchangeService 对象来创建和发送电子邮件。

var credentials = new OAuthCredentials(token);
var ews = new ExchangeService();
ews.Credentials = credentials;
ews.Url = endpointUrl;

var email = new EmailMessage(ews);
...

email.Send();

https://learn.microsoft.com/zh-cn/exchange/client-developer/web-service-reference/ews-managed-api-reference-for-exchange

未来的方法是使用Microsoft Graph,但我对此不太熟悉。 https://docs.microsoft.com/zh-cn/graph/outlook-mail-concept-overview?view=graph-rest-1.0


对不起,请问 endpointUrl 的值是多少? - genius26
没事了!我找到了我要找的答案:https://quicklaunch.ucworkspace.com/support/solutions/articles/3000079710-determining-the-exchange-web-services-ews-url。 - genius26

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接