Last active
December 5, 2022 12:29
-
-
Save mirontoli/60c028b6658a5485ed333ca57cae7270 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
//Slightly adjusted from https://github.com/pnp/pnpcore/blob/dev/samples/Demo.Console.Minimal/Program.cs | |
//The goal is to send an email using Graph API and by authenticating through PnP Management Shell | |
//Without a custom app registration | |
//corresponding commands: https://pnp.github.io/cli-microsoft365/cmd/outlook/mail/mail-send/ | |
//and | |
using AngleSharp.Dom; | |
using Microsoft.Extensions.DependencyInjection; | |
using Microsoft.Extensions.Hosting; | |
using PnP.Core.Auth; | |
using PnP.Core.Services; | |
using System.Net.Http.Headers; | |
using System.Net.Http.Json; | |
using System.Net.Mail; | |
using System.Security; | |
using System.Text.Json.Nodes; | |
using System.Text.Json.Serialization; | |
string siteUrl = "https://contoso.sharepoint.com"; | |
var account = "[email protected]"; | |
SecureString sec = new SecureString(); | |
string pwd = ""; | |
pwd.ToCharArray().ToList().ForEach(sec.AppendChar); | |
sec.MakeReadOnly(); | |
var host = Host.CreateDefaultBuilder() | |
.ConfigureServices((context, services) => | |
{ | |
services.AddPnPCore(options => | |
{ | |
options.DefaultAuthenticationProvider = new UsernamePasswordAuthenticationProvider(null, null, account, sec); | |
}); | |
}) | |
.UseConsoleLifetime() | |
.Build(); | |
await host.StartAsync(); | |
using (var scope = host.Services.CreateScope()) | |
{ | |
var pnpContextFactory = scope.ServiceProvider.GetRequiredService<IPnPContextFactory>(); | |
using (var context = await pnpContextFactory.CreateAsync(new Uri(siteUrl))) | |
{ | |
var token = await context.AuthenticationProvider.GetAccessTokenAsync(new Uri("https://graph.microsoft.com/")); | |
string mp = "{\"message\": {\"subject\": \"Meet for lunch?\",\"body\": {\"contentType\": \"Text\",\"content\": \"The new cafeteria is open.\"},\"toRecipients\": [{\"emailAddress\": {\"address\": \"[email protected]\"}}]}}"; | |
var smp = new StringContent(mp, System.Text.Encoding.UTF8, "application/json"); | |
var uri = "https://graph.microsoft.com/v1.0/me/sendMail"; | |
var client = new HttpClient(); | |
client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", token); | |
var response = await client.PostAsync(uri, smp); | |
response.EnsureSuccessStatusCode(); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment