Office365是微软提供的一套云端办公套件,包括了电子邮件、日历、文件存储和共享等功能。在C#中使用Oauth2协议发送电子邮件可以实现与Office365的集成。
在C#中使用Oauth2发送电子邮件的具体步骤如下:
示例代码如下:
using System;
using System.Net.Http;
using System.Net.Http.Headers;
using System.Threading.Tasks;
public class Program
{
public static async Task Main(string[] args)
{
string clientId = "YourClientId";
string clientSecret = "YourClientSecret";
string tenantId = "YourTenantId";
string accessToken = await GetAccessToken(clientId, clientSecret, tenantId);
string emailEndpoint = "https://graph.microsoft.com/v1.0/me/sendMail";
string emailContent = "Your email content";
string recipientEmail = "recipient@example.com";
string senderEmail = "sender@example.com";
string subject = "Your email subject";
await SendEmail(accessToken, emailEndpoint, emailContent, recipientEmail, senderEmail, subject);
}
private static async Task<string> GetAccessToken(string clientId, string clientSecret, string tenantId)
{
string tokenEndpoint = $"https://login.microsoftonline.com/{tenantId}/oauth2/v2.0/token";
string scope = "https://graph.microsoft.com/.default";
using (HttpClient client = new HttpClient())
{
var requestContent = new FormUrlEncodedContent(new[]
{
new KeyValuePair<string, string>("grant_type", "client_credentials"),
new KeyValuePair<string, string>("client_id", clientId),
new KeyValuePair<string, string>("client_secret", clientSecret),
new KeyValuePair<string, string>("scope", scope)
});
var response = await client.PostAsync(tokenEndpoint, requestContent);
var responseContent = await response.Content.ReadAsStringAsync();
// Parse the access token from the response
// ...
return accessToken;
}
}
private static async Task SendEmail(string accessToken, string emailEndpoint, string emailContent, string recipientEmail, string senderEmail, string subject)
{
using (HttpClient client = new HttpClient())
{
client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", accessToken);
var email = new
{
message = new
{
subject = subject,
body = new
{
contentType = "Text",
content = emailContent
},
toRecipients = new[]
{
new
{
emailAddress = new
{
address = recipientEmail
}
}
},
from = new
{
emailAddress = new
{
address = senderEmail
}
}
}
};
var requestContent = new StringContent(JsonConvert.SerializeObject(email), Encoding.UTF8, "application/json");
var response = await client.PostAsync(emailEndpoint, requestContent);
var responseContent = await response.Content.ReadAsStringAsync();
// Handle the response
// ...
}
}
}
以上代码演示了如何使用C#和Oauth2协议发送电子邮件。在实际使用中,需要替换相应的参数,如客户端ID、客户端密钥、租户ID、收件人邮箱、发件人邮箱和邮件内容等。
请注意,以上示例代码仅供参考,实际使用时需要根据具体情况进行适当的修改和调整。
领取专属 10元无门槛券
手把手带您无忧上云