-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathProgram.cs
More file actions
87 lines (71 loc) · 3.31 KB
/
Program.cs
File metadata and controls
87 lines (71 loc) · 3.31 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
using System.Net.Http.Headers;
using System.Text;
using System.Text.Json;
class Program
{
static async Task Main(string[] args)
{
// azure app registrations info
string clientId = "####";
string clientSecret = "####";
string tenantId = "####";
string tokenEndpoint = $"https://login.microsoftonline.com/{tenantId}/oauth2/v2.0/token";
// create an httpclient
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", "https://graph.microsoft.com/.default"),
});
// retrieve access token
HttpResponseMessage response = await client.PostAsync(tokenEndpoint, requestContent);
string responseContent = await response.Content.ReadAsStringAsync();
var tokenResponse = JsonSerializer.Deserialize<JsonElement>(responseContent);
string accessToken = tokenResponse.GetProperty("access_token").GetString();
// Console.WriteLine(accessToken);
string mailUser = "";
string sendMailEndpoint = $"https://graph.microsoft.com/v1.0/users/{mailUser}/sendMail";
var message = new Dictionary<string, object>()
{
{"message", new Dictionary<string, object>()
{
{"subject", "Test email using graph api, subject 2"},
{"body", new Dictionary<string, object>()
{
{"contentType", "Text"},
{"content", "Hello this is a successful message send by microsoft graph api with dot framework, message two"}
}
},
{"toRecipients", new object[]{
new Dictionary<string, object>()
{
{"emailAddress", new Dictionary<string, object>()
{
{"address", ""}
}
}
}
}},
}
},
{"saveToSentItems", "true"}
};
var jsonMessage = JsonSerializer.Serialize(message);
var content = new StringContent(jsonMessage, Encoding.UTF8, "application/json");
// post request to send the email
var request = new HttpRequestMessage(HttpMethod.Post, sendMailEndpoint);
request.Headers.Authorization = new AuthenticationHeaderValue("Bearer", accessToken);
request.Content = content;
HttpResponseMessage sendMailResponse = await client.SendAsync(request);
string sendMailResponseContent = await sendMailResponse.Content.ReadAsStringAsync();
if (sendMailResponse.IsSuccessStatusCode){
Console.WriteLine("Email send successfully");
}else{
Console.WriteLine("Failed to send the email");
}
}
}
}