Skip to content

Instantly share code, notes, and snippets.

@ahelland
Created December 9, 2016 18:27
Show Gist options
  • Save ahelland/1dc13e873298fbfa6dceb0f3537aadb8 to your computer and use it in GitHub Desktop.
Save ahelland/1dc13e873298fbfa6dceb0f3537aadb8 to your computer and use it in GitHub Desktop.
Azure Function for sending a mail as a user after authenticating using the Password Grant flow
#r "Newtonsoft.Json"
using System;
using System.Text;
using System.Threading.Tasks;
using System.Net.Http;
using Newtonsoft.Json;
using static System.Environment;
using System.Collections.Generic;
public async static void Run(string input, TraceWriter log)
{
log.Info($"C# manually triggered function called with input: {input}");
var domain = "contoso.onmicrosoft.com";
var user = "[email protected]";
var pw = "password";
var clientId = "guid-from-portal";
var resource = "https://graph.microsoft.com";
HttpClient client = new HttpClient();
string requestUrl = $"https://login.microsoftonline.com/{domain}/oauth2/token";
string request_content = $"grant_type=password&resource={resource}&client_id={clientId}&username={user}&password={pw}&scope=openid+Mail.Send";
HttpRequestMessage request = new HttpRequestMessage(HttpMethod.Post, requestUrl);
try
{
request.Content = new StringContent(request_content, Encoding.UTF8, "application/x-www-form-urlencoded");
}
catch (Exception x)
{
var msg = x.Message;
}
HttpResponseMessage response = await client.SendAsync(request);
string responseString = await response.Content.ReadAsStringAsync();
log.Info(responseString);
GenericToken token = JsonConvert.DeserializeObject<GenericToken>(responseString);
var at = token.access_token;
var me = await GetUserInfo(at);
log.Info($"Display Name:{me.displayName}{NewLine}Upn:{me.userPrincipalName}{NewLine}Preferred Language:{me.preferredLanguage}");
await SendMail(at,log);
}
private static async Task<AADUser> GetUserInfo(string token)
{
string graphRequest = $"https://graph.microsoft.com/v1.0/me/";
var authHeader = "Bearer " + token;
HttpClient client = new HttpClient();
client.DefaultRequestHeaders.TryAddWithoutValidation("Authorization", authHeader);
var response = await client.GetAsync(new Uri(graphRequest));
string content = await response.Content.ReadAsStringAsync();
var user = JsonConvert.DeserializeObject<AADUser>(content);
return user;
}
private static async Task<MailMessage> SendMail(string token, TraceWriter log)
{
//https://graph.microsoft.io/en-us/docs/api-reference/v1.0/api/user_sendmail
HttpClient client = new HttpClient();
var authHeader = "Bearer " + token;
string requestUrl = $"https://graph.microsoft.com/v1.0/me/sendMail";
var baseEmail = new EmailAddress { name = "Alice", address = "[email protected]" };
var fromEmail = new EmailAddress { name = "Bob", address = "[email protected]" };
var from = new From { emailAddress = fromEmail };
var send = new Sender { emailAddress = fromEmail };
var recList = new List<ToRecipient>();
recList.Add(new ToRecipient { emailAddress = baseEmail });
var replyAddress = new List<ReplyTo>();
replyAddress.Add(new ReplyTo { emailAddress = fromEmail });
var bcc = new List<BccRecipient>();
var cc = new List<CcRecipient>();
var cats = new List<string>();
var body = new Body { contentType = "text", content = "Hello World" };
var draft = new MailItem { toRecipients = recList,sender=send,from = from, bccRecipients=bcc,ccRecipients=cc, replyTo=replyAddress, categories=cats, body = body, subject = "Hello World" };
var Message = new MailMessage { Message = draft, SaveToSentItems = "true" };
string request_content = JsonConvert.SerializeObject(Message);
HttpRequestMessage request = new HttpRequestMessage(HttpMethod.Post, requestUrl);
try
{
client.DefaultRequestHeaders.TryAddWithoutValidation("Authorization", authHeader);
request.Content = new StringContent(request_content, Encoding.UTF8, "application/json");
}
catch (Exception x)
{
var exception = x.Message;
}
HttpResponseMessage response = await client.SendAsync(request);
string responseString = await response.Content.ReadAsStringAsync();
log.Info(responseString);
MailMessage msg = JsonConvert.DeserializeObject<MailMessage>(responseString);
return msg;
}
public class GenericToken
{
public string token_type { get; set; }
public string scope { get; set; }
public string resource { get; set; }
public string access_token { get; set; }
public string refresh_token { get; set; }
public string id_token { get; set; }
public string expires_in { get; set; }
}
public class AADUser
{
public string displayName { get; set; }
public string givenName { get; set; }
public string surname { get; set; }
public string mail { get; set; }
public string preferredLanguage { get; set; }
public string userPrincipalName { get; set; }
public string mobilePhone { get; set; }
}
public class MailMessage
{
public MailItem Message { get; set; }
public string SaveToSentItems { get; set; }
}
public class EmailAddress
{
public string name { get; set; }
public string address { get; set; }
}
public class BccRecipient
{
public EmailAddress emailAddress { get; set; }
}
public class Body
{
public string contentType { get; set; }
public string content { get; set; }
}
public class CcRecipient
{
public EmailAddress emailAddress { get; set; }
}
public class From
{
public EmailAddress emailAddress { get; set; }
}
public class ReplyTo
{
public EmailAddress emailAddress { get; set; }
}
public class Sender
{
public EmailAddress emailAddress { get; set; }
}
public class ToRecipient
{
public EmailAddress emailAddress { get; set; }
}
public class UniqueBody
{
public string contentType { get; set; }
public string content { get; set; }
}
public class MailItem
{
public List<BccRecipient> bccRecipients { get; set; }
public Body body { get; set; }
public string bodyPreview { get; set; }
public List<string> categories { get; set; }
public List<CcRecipient> ccRecipients { get; set; }
public string changeKey { get; set; }
public string conversationId { get; set; }
public string createdDateTime { get; set; }
public From from { get; set; }
public bool hasAttachments { get; set; }
public string id { get; set; }
public string importance { get; set; }
public string inferenceClassification { get; set; }
public string internetMessageId { get; set; }
public bool isDeliveryReceiptRequested { get; set; }
public bool isDraft { get; set; }
public bool isRead { get; set; }
public bool isReadReceiptRequested { get; set; }
public string lastModifiedDateTime { get; set; }
public string parentFolderId { get; set; }
public string receivedDateTime { get; set; }
public List<ReplyTo> replyTo { get; set; }
public Sender sender { get; set; }
public string sentDateTime { get; set; }
public string subject { get; set; }
public List<ToRecipient> toRecipients { get; set; }
public UniqueBody uniqueBody { get; set; }
public string webLink { get; set; }
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment