SharePoint-hosted apps: Send Emails using SharePoint REST API
var sendEmails = function (emailCollection) {
var oDeferred = $.Deferred(),
email, iCounter = 0;
// create an object for a http request
var oHttpRequest = {
url: "{0}/_api/SP.Utilities.Utility.SendEmail",
type: "POST",
contentType: "application/json; odata=verbose",
headers: {
"accept": "application/json; odata=verbose",
"contentType": "application/json; odata=verbose",
"X-RequestDigest": $("#__REQUESTDIGEST").val()
}
}
oHttpRequest.url = String.format(oHttpRequest.url, _spPageContextInfo.siteAbsoluteUrl);
// Iterate the email collections and send emails
for (email in emailCollection) {
oHttpRequest.data = JSON.stringify({
'properties': {
'__metadata': { 'type': 'SP.Utilities.EmailProperties' },
'From': emailCollection[email].From,
'To': { 'results': [emailCollection[email].To] },
'Subject': emailCollection[email].Subject,
'Body': emailCollection[email].Body
}
});
try {
return $.ajax(oHttpRequest)
.done(function () {
iCounter += 1;
if (iCounter == emailCollection.length) // Once all the emails are send then resolve the promise object.
oDeferred.resolve();
}).fail(function (xhr, textStatus, errorThrown) {
alert(textStatus);
});
}
catch (err) {
err.message;
}
}
return oDeferred.promise();
}
// Example Email Object
var emailCollection = [];
var oEmail = {};
oEmail["From"] = "salman.malik@de.sp.com";
oEmail["To"] = "salman.malik@de.sp.com";
oEmail["Subject"] = "Test Email From Sharepoint App";
oEmail["Body"] = "It is a test email generated from Sharepoint App";
emailCollection.push(oEmail);
sendEmails(emailCollection);
No comments:
Post a Comment