December 8, 2016

How to send an Email having HTML formatted Body through SharePoint Add-in

While working with SharePoint Add-ins (SharePoint Hosted App), there was requirement to send an Email to users. We can do it through REST API with AJAX call in SharePoint but my concern was how I can send an email with HTML formatted body. 

Remember, The recipients users should be valid SharePoint Users. Emails cannot be sent to non-SharePoint users and external users.

Solution: Here is how I achieved it !
We have to include "AdditionalHeaders" in the mailObject which is required to specify the content type of the email, here is HTML. Without using this header, the email will be sent as a plain text, and the HTML formatting will be ignored.

function sendEMail(toList, subject, mailContent) {
    appweburl = decodeURIComponent(getQueryStringParameter('SPAppWebUrl'));
var restUrl = appweburl + "/_api/SP.Utilities.Utility.SendEmail",
restHeaders = { "Accept": "application/json;odata=verbose", "X-RequestDigest": $("#__REQUESTDIGEST").val(), "Content-Type": "application/json;odata=verbose" }, mailObject = { 'properties': { '__metadata': { 'type': 'SP.Utilities.EmailProperties' }, 'To': { 'results': toList }, 'Subject': subject, 'Body': mailContent, "AdditionalHeaders": { "__metadata":{ "type": "Collection(SP.KeyValue)" }, "results": [ { "__metadata": { "type": 'SP.KeyValue' }, "Key": "content-type", "Value": 'text/html', "ValueType": "Edm.String" } ] }
} }; return $.ajax({ contentType: "application/json", url: restUrl, type: "POST", data: JSON.stringify(mailObject), headers: restHeaders }); }
The above method can be called from SharePoint Add-in or Client Side code as shown below.
//An array of valid SharePoint Users, External users & emails are not supported.
var toUserList = [,]
//Subject of the Email.
var mailSubject = "Download documents";
//HTML formatted Email Body.
var mailContent = "<h3>Here are all documents</h3><p>Links</p><div>document 1</div>";
sendEMail(toUserList, mailSubject , mailContent).done(function (response) {
    console.log("E-Mail Sent successfully.");
}).fail(function () {
    console.error("Error while sending an E-Mail.");
Hope this will help!

If you have any questions you can reach out our SharePoint Consulting team here.

No comments:

Post a Comment