sending an email through sharepoint REST api in javascript - javascript

I have been trying to send an email to the sharepoint user on click of a button in a client side web page.
I am trying to use the REST API using JSOM
and the code looks like below.
sendEmail("user#domain.com", "rec#domain.com", "test", "test-email");
function sendEmail(from, to, body, subject) {
var siteurl = _spPageContextInfo.webServerRelativeUrl;
var urlTemplate = siteurl + "/_api/SP.Utilities.Utility.SendEmail";
$.ajax({
contentType: 'application/json',
url: urlTemplate,
type: "POST",
data: JSON.stringify({
'properties': {
'__metadata': { 'type': 'SP.Utilities.EmailProperties' },
'From': from,
'To': { 'results': [to] },
'Body': body,
'Subject': subject
}
}
),
headers: {
"Accept": "application/json;odata=verbose",
"content-type": "application/json;odata=verbose",
"X-RequestDigest": $("#__REQUESTDIGEST").val()
},
success: function (data) {
alert("Eposten ble sendt");
},
error: function (err) {
alert(err.responseText);
debugger;
}
});
}
The issue what am facing here is:
1. Am getting an error 404 Not Found => does it mean my server does not have the utilities api?
2. When i tried (siteurl + "/_api/SP.Utilities.Utility.SendEmail") in browser it gives 404 not found.
Let me know how to resolve this issue.(Note: i dont have access to central admin).
(or)
Is there any other way to send an email without using workflow? or to call an workflow from a script?

Add following code to send E-Mail through Rest API in SharePoint.
Code get from this Link
$.ajax({
contentType: 'application/json',
url: urlEmail,
type: "POST",
data: JSON.stringify({
'properties': {
'__metadata': { 'type': 'SP.Utilities.EmailProperties' },
'Body': 'Lorem ipsum dolor sit amet...',
'To' : { 'results': ['admin#codeplayandlearn.com'] },
'Subject': "E-Mail From REST API";
}
}),
headers: {
"Accept": "application/json;odata=verbose",
"content-type": "application/json;odata=verbose",
"X-RequestDigest": $("#__REQUESTDIGEST").val()
},
success: function (data) {
alert("Email Send Successful.");
},
error: function (err) {
alert(err.responseText);
}
});

Related

An unexpected 'StartObject' node was found when reading from the JSON reader. A 'PrimitiveValue' node was expected

I'm using a rest API call to add an item to my 'Email' people picker column in a Sharepoint list. But I'm not able to add it due to this error.
I've tried keeping the payload without email but it still doesn't solve it
Code is self-explanatory but I will give you some insight if you want it
setPeoplesColumn: function()
{
console.log("user id is "+addressBookListRestService.UserID);
var item=
{
"__metadata":
{
"type": 'SP.Data.Address_x0020_BookListItem'
},
"Title": 'Some Dude',
'EmailId' :
{
"results" : [_spPageContextInfo.userId]
}
};
$.ajax
({
url: _spPageContextInfo.webAbsoluteUrl + "/_api/web/lists/GetByTitle('Address Book')/items",
type: "POST",
headers:
{
"accept": addressBookListRestService.acceptHeaderValue,
"X-RequestDigest": addressBookListRestService.requestDigestHeaderValue,
"content-Type": addressBookListRestService.contentTypeHeaderValue
},
data: JSON.stringify(item),
success: function(data)
{
console.log("success is "+(data.d.result));
console.log("ID is "+JSON.stringify(data.d.results));
},
error: function(error) {
console.log("failure is "+JSON.stringify(error));
}
});//end of ajax function
},
The error should be json data format.
My test script based on your demo(Email people field allow multiple selections).
<script type="text/javascript">
function setPeoplesColumn() {
console.log("user id is " + _spPageContextInfo.userId);
var item =
{
"__metadata":
{
"type": 'SP.Data.Address_x0020_BookListItem'
},
"Title": 'Some Dude',
'EmailId':
{
"results": [_spPageContextInfo.userId]
}
};
$.ajax
({
url: _spPageContextInfo.webAbsoluteUrl + "/_api/web/lists/GetByTitle('Address Book')/items",
type: "POST",
headers:
{
"Accept": "application/json;odata=verbose",
"Content-Type": "application/json;odata=verbose",
"X-RequestDigest": $("#__REQUESTDIGEST").val()
},
data: JSON.stringify(item),
success: function (data) {
console.log("success is " + (data.d));
console.log("ID is " + JSON.stringify(data.d));
},
error: function (error) {
console.log("failure is " + JSON.stringify(error));
}
});//end of ajax function
}
</script>
<input id="Button1" type="button" onclick="setPeoplesColumn()" value="button" />

How to do a service call for 'POST' method?

How to do a service call for 'POST' method for the payload with the headers described below?
Payload for the service:
{
"SupplierPOPrint": {
"ErrorFlag": "Status Code: 20, Message ID: 505",
"ResultMessage": "Integration Service: Unable to find a routing corresponding to the incoming request message."
}
}
headers: { "Accept": "application/json", "Content-Type": "text/xml", },
function poPrint() {
$.ajax({
url: '/wps/proxy/http/10.249.114.31:8009/soa-infra/resources/Supp‌​lierPortal/CreateSup‌​plierPOPrintService!‌​1.0/CreateSupplierPO‌​PrintService/Create'‌​,
type: 'POST',
dataType: 'json',
data: new XMLSerializer().serializeToString(updatedTemplate),
crossDomain: true,
success: function(poPrintData) {
console.log("poPrintData", poPrintData);
poPrintDetails = poPrintData.SupplierPOPrint;
console.log("poPrintDetails", poPrintDetails);
poPrintTemplate = generatepoPrint(poPrintData);
$("#poPrintOutput").html(poPrintTemplate);
},
error: function(data) {
console.log("Update Content Failed", data);
}
});
}

Javascript with SharePoint 2013 REST Endpoint "INSERT" into List?

Here are what i'm going to use:
SharePoint 2013
Javascript
REST Endpoint
SharePoint List (called: "Announcements")
WebSite (called: "example.com")
Refs:
http://www.plusconsulting.com/blog/2013/05/crud-on-list-items-using-rest-services-jquery/
https://msdn.microsoft.com/EN-US/library/dn292552.aspx
Very simply:
How do i INSERT a new item (row) inside the List please?
I tried:
$.ajax({
url: "https://example.com/_api/web/lists/getbytitle('Announcements')/items",
type: "POST",
contentType: "application/json;odata=verbose",
data: JSON.stringify( { '__metadata': { 'type': 'SP.Data.AnnouncementListItem' }, "Title": "New Announcement!" } ),
headers: {
"Accept": "application/json;odata=verbose",
"Authorization": "Bearer " + accessToken
"X-RequestDigest": form digest value,
"IF-MATCH": etag,
},
success: function (data) {
console.log(data);
},
error: function (data) {
console.log(data);
}
});
Then i know a lot of things go wrong especially in headers section. But what does it mean by:
Authorization
accessToken
X-RequestDigest
IF-MATCH
.. and then HOW TO get these values (with JavaScript)? So that:
What are always the exact required fields there?
And how/where to get these values from?
I still can not find a simple and complete example about doing this Update / Insert properly.
So there are two ways that I have used to submit an item to a list, the jQuery library SPServices and REST API's. SPServices is really well documented here. Using REST API's is much faster and pretty easy too!
function createListItem(itemProperties, success, failure) {
$.ajax({
url: "https://example.com/_vti_bin/listdata.svc/Announcements",
type: "POST",
processData: false,
contentType: "application/json;odata=verbose",
data: JSON.stringify(itemProperties),
headers: {
"Accept": "application/json;odata=verbose"
},
success: function(data) {
success(data.d);
},
error: function(data) {
// failure(data.responseJSON.error);
alert("error");
}
});
}
First thing I am doing above is creating a function that you can call whenever you want to create a new list item. The parameter itemProperties can be populated with the fields which you need, see below.
var Title = "Title";
var Answer = "Answer";
var userid = _spPageContextInfo.userId;
var taskProperties = {
'Title': Title,
'Answer': Answer,
'UserId': userid
};
Then all we have to do is call this function with the new variable we just declared.
createListItem(taskProperties, function(task) {
alert("Thank you for your input!");
},
function(error) {
console.log(JSON.stringify(error));
}
);
Actually jsfiddle which you have posted in the previous commend is not the REST . you just use the SharePoint client object model. find below the REST API model I hope it will work
var cat = {
"__metadata": { "type": ItemType },
"Title": "GenIT-Issue",
}
$.ajax({
url: _spPageContextInfo.siteAbsoluteUrl + "/_api/web/lists/getbytitle('Tickets')/items",
type: "POST",
contentType: "application/json;odata=verbose",
data: JSON.stringify(cat),
headers: {
"Accept": "application/json;odata=verbose",
"X-RequestDigest": $("#__REQUESTDIGEST").val()
},
success: function (data) {
},
error: function (data) {
}
});
I run this code inside my SharePoint page so there is no authentication required. it will run on current user privilege

how to get access token from bitly using password and username?

$.ajax({
url: 'https://api-ssl.bitly.com/oauth/access_token',
type: 'POST',
contentType: 'application/x-www-form-urlencoded',
dataType: 'json',
data: { Authorization: "Basic " + btoa('myusername' + ":" + 'mypassword#123') },
success: function (result) {
console.log(result);
},
error: function () {
alert("Cannot get data");
}
});
I am trying to get access token from bitly api by providing username and password but it is showing invalid_client_authorization error. Does any one have idea on the same?
Bitly documentation : http://dev.bitly.com/authentication.html#resource_owner_credentials
You are concatenating your username with your authorization header.
Your authorization and content-type should go in the headers object.
There is no 'type' property on jquery ajax method, you probably meant 'method'.
Also, you can't send both dataType:'json' and set the content-type to 'application/x-www-form-urlencoded'
$.ajax({
url: 'https://api-ssl.bitly.com/oauth/access_token',
methdo: 'POST',
contentType: '',
dataType: 'json',
headers: {
'Authorization' : 'Basic ' + [INSERT YOUR HASH HERE],
'Content-Type' : 'application/x-www-form-urlencoded',
}
data: { $.serialize({
username: YOURUSERNAME,
password: YOURPASSWORD
})},
success: function (result) {
console.log(result);
},
error: function () {
alert("Cannot get data");
}
});
This should do it
Fixed #goncalomarques answer:
Removed top level "contentType" and "dataType"
Removed data object (otherwise username and password is sent as clear text, in addition to the hashed username and password in the header)
renamed "methdo" to "method"
Explicitly used btoa() to get Base 64 encoded hash (be aware, does not work in older IE versions)
$.ajax({
url: 'https://api-ssl.bitly.com/oauth/access_token',
method: 'POST',
headers: {
'Authorization': 'Basic ' + btoa(YOURUSERNAME + ':' + YOURPASSWORD),
'Content-Type': 'application/x-www-form-urlencoded',
},
success: function(result) {
console.log("success");
console.log(result);
},
error: function(response) {
console.log("Cannot get data");
console.log(response);
}
});
Note:
I have this example working, but was unable to get it working with the built-in Stackoverflow editor ("Run snippet") due to cross origin exceptions.

Paypal Java script integration

Want to integrate Paypal with my mobile web application. I tried to get the access token using client id and secret id but unable to get the access token.
Below is the sample Ajax call with I am making to retrieve the access token.
function getAccessToken(){
$.ajax({
url:"https://api.sandbox.paypal.com/v1/oauth2/token/",
type:"POST",
data : {"grant_type":"client_credentials"},
beforeSend: function (request)
{
request.setRequestHeader("Accept", "application/json");
request.setRequestHeader("Accept-Language", "en_US");
request.setRequestHeader("Authorization", "abc XXXXX:XXXXXXXXXXXXX");
},
success: function(data) {
alert(data);
},
error: function(e, messgae,type){
alert("Error" + e +" "+messgae+" type "+type);
}
});
I am unable to retrive the access token from the server.
Can anyone please tell me how can I integrate Paypal with my mobile web application using java script?
after a series of try and fail I found the correct AJAX call:
$.ajax({
headers: {
"Accept": "application/json",
"Accept-Language": "en_US",
"Authorization": "Basic "+btoa("**<Client ID>:<Secret>**")
},
url: "https://api.sandbox.paypal.com/v1/oauth2/token",
type: "POST",
data: "grant_type=client_credentials",
complete: function(result) {
alert(JSON.stringify(result));
},
});
You need to replace Client ID:Secret with the one that you find on your Developer Dashboard, for example AxxhGDh:hudh-X-h8qi
Above example doesn't works, below works for me:
var parameter = {
"grant_type": "client_credentials",
"username": "<username>",
"password": "<password>"
}
$.ajax({
headers: {
"Accept": "application/json",
"Accept-Language": "en_US",
"Authorization": "Basic <your auth key>"
},
url: "https://api.sandbox.paypal.com/v1/oauth2/token",
type: "POST",
data: parameter,
complete: function (result) {
alert(JSON.stringify(result));
},
})

Categories