我试图使用Office 365帐户和Oauth2在c#中发送电子邮件。
目前,我可以获取令牌,但不确定如何使用该令牌并发送电子邮件。
System.Net.Mail不支持OAuth或OAuth2。
我看到了Mailkit,但是示例都是针对Google Mail的,并没有看到适用于Office 365的示例,所以我不太确定从哪里开始。
有关在 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);
}
使用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);
}
}
}
}
您可以使用 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();
未来的方法是使用Microsoft Graph,但我对此不太熟悉。 https://docs.microsoft.com/zh-cn/graph/outlook-mail-concept-overview?view=graph-rest-1.0