Office 365 send email using JavaScript (REST)

I have a fairly simple requirement for some JavaScript (jQuery) to send an email.   This is within the code for a SharePoint Online page (Office 365).

My initial thinking was to do a HTTP POST request to the Office 365 REST endpoint, but nothing could have prepared me for the next few hours of my day.

I had to jump through a few hoops, and perform backflips while juggling – and THEN changed tack entirely.   I thought I’d share my observations – and some sample code/link.

This was my starting point (MSDN) :    Send a new message on the fly (REST)

I wrangled with it for a few hours :

  • SharePoint hosted code (JS), calling to https://outlook.office365.com was resulting in a 401 – due to a X-Domain call.
  • HTTP POST with JSONP doesn’t work – only for GET
  • CORS is what was messing it up – 401’ing the request
  • Even trialling with the new http://graph.microsoft.com – same problem
  • Suggestions via Twitter were to do an Azure AD app – TO SEND AN EMAIL !!
  • I even found one ridiculous solution that was to create workflow from Visual Studio or SharePoint Designer – and then CALL it from CSOM.    #WTF !!

A colleague mentioned “surely SharePoint has something to send an email” – it could then process the email traffic SERVER SIDE.   

That was an unholy yee-haar gold nugget of joy.

Posting from my jQuery back to SharePoint Online is a simple REST call.   And, it does NOT suffer from X-Domain or CORS.    

http://tenant/_api/SP.Utilities.Utility.SendEmail

There’s a blog post that I found, with a great code sample – and it’s now working for me :

Sending email with SharePoint and jQuery

Just note that the recipient is limited to a valid SharePoint user for security reasons.    (within the same tenant)

So – it’s the simply “KISS” principle – keep it simple, stupid.   

😉

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s