How do I send an email in JavaScript?

Did you know that you can send an email in JavaScript and not rely on a workflow? It’s not only possible, but through the use of the PreSaveAction() function, I have all but eliminated the use of clunky and unreliable workflows.

But what about not having an id yet when saving a newform.aspx you ask? That’s for the next post. For now, here’s the actual code that resides in my JSUtils.js file.

The code comments pretty well explain everything and if you want your code to take action in case the email fails, pass responseRequired as true . All global variables are added to the namespace carved out to prevent collisions.


"use strict";
var MyORG = window.MyORG || {};
MyORG.Response = false;
MyORG.From = "do-not-reply@ugov.gov";
MyORG.To = [];
MyORG.CC = [];
MyORG.BCC = [];

function PreSaveAction() {
    if (!sendNotification(MyORG.From, MyORG.To, MyORG.CC, MyORG.BCC, MyORG.Body, MyORG.Subject, true)) {
        alert("Error Sending Mail!  Please notify the Requirement Owner(s) that this item is waiting for them.");
    }
}

///////////////////////////////////////////////////////////////////////////////////
// All addresses must be present in the User Information List.                   //
// From, To, Body and Subject are manadatory fields.                             //
// To must be an array even if only one value is included.                       //
// CC and BCC must be arrays even if empty.                                      //
// The code below attempts to correct deficiencies, but the onus is on the user. //
//                                                                               //
// If a response is required, pass responseRequired as true.  This introduces a  //
// one second delay to capture a response, so use it sparingly.  The function    //
// does set console.log to true or false for troubleshooting purposes regardless //
// of responseRequired setting.                                                  //
///////////////////////////////////////////////////////////////////////////////////
function sendNotification(from, to, cc, bcc, body, subject, responseRequired) {
    if (typeof(from) == "undefined" || from == null || from == "" ||
        typeof(to) == "undefined" || to == null || to == "" ||
        typeof(body) == "undefined" || body == null || body == "" ||
        typeof(subject) == "undefined" || subject == null || subject == "")
    {
        return false;
    }
    if (typeof(cc) == "undefined" || cc == null || cc == "") {cc = []}
    if (typeof(bcc) == "undefined" || bcc == null || bcc == "") {bcc = []}
    if (typeof(to) == "string") {to = [to]}
    if (typeof(cc) == "string") {cc = [cc]}
    if (typeof(bcc) == "string") {bcc = [bcc]}
    
    if (responseRequired) {
        // Like all async functions in SP.js, SP.SOD.executeFunc will not return a value,
        // so we will use a global variable and setTimeout to get around the problem.
        // It's butt-ugly, but it works...
        MyORG.Response = false;
        setTimeout(SP.SOD.executeFunc('sp.js', 'SP.ClientContext', sendNotificationEmail(from, to, cc, bcc, body, subject)), 1000);
        return MyORG.Response;
    } else {
        SP.SOD.executeFunc('sp.js', 'SP.ClientContext', sendNotificationEmail(from, to, cc, bcc, body, subject));
    }
}
function sendNotificationEmail(from, to, cc, bcc, body, subject) {
    var siteurl = _spPageContextInfo.siteServerRelativeUrl;
    $.ajax({
        contentType: 'application/json',
        url: "/sites/yoursitecollection/_api/SP.Utilities.Utility.SendEmail",
        type: "POST",
        async: false,
        data: JSON.stringify({
            'properties': {
                '__metadata': {
                    'type': 'SP.Utilities.EmailProperties'
                },
                'From': from,
                'To': {
                    'results': to
                },
                'CC': {
                    'results': cc
                },
                'BCC': {
                    'results': bcc
                },
                'Body': body,
                'Subject': subject,
                "AdditionalHeaders":
                {"__metadata":
                    {"type":"Collection(SP.KeyValue)"},
                    "results":
                    [ 
                        {
                            "__metadata": {"type": 'SP.KeyValue'},
                            "Key": "content-type",
                            "Value": "text/html",
                            "ValueType": "Edm.String"
                        }
                    ]
                }
            }
        }),
        headers: {
            "Accept": "application/json;odata=verbose",
            "content-type": "application/json;odata=verbose",
            "X-RequestDigest": $("#__REQUESTDIGEST").val()
        },
        success: function(data) {
            MyORG.Response = true;
            console.log('Email Sent Successfully');
        },
        error: function(err) {
            console.log('Error in sending Email: ' + JSON.stringify(err));
        }
    });
}
Advertisements

One thought on “How do I send an email in JavaScript?

  1. Pingback: Sending Emails from SharePoint Solutions Using Microsoft Flow | Marc D Anderson's Blog

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 )

Google+ photo

You are commenting using your Google+ 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 )

w

Connecting to %s