How to add more ccRecipients in microsoft graph? - json

I'm using Microsoft Graph to connect with Outlook. Can someone please help me with my issue. I need to add more than one ccRecipient and bccRecipient. My web application sends, receives and reads emails through API. But I cant send email to more than one cc and bcc recipient. This is the function i`m using to send email.
edit: Right now function does not have two ccRecipients and two bccRecipients in JSON. I have tried in many different ways but when i test it in microsoft graph-explorer it fails to send on more than one address.
function sendEmail(){
getAccessToken(function(accessToken) {
if (accessToken) {
// Create a Graph client
var client = MicrosoftGraph.Client.init({
authProvider: (done) => {
// Just return the token
done(null, accessToken);
}
});
var recipient = $("#recipient").val();
var subject = $("#subject").val();
var carbon_copies = $("#carbon_copies").val();
var blind_carbon_copies = $("#blind_carbon_copies").val();
var filename_attachment = $("#filename").text();
var attachments_base64 = $("#attachment_base64").val();
var attachments_base64_replaced = attachments_base64.substring(attachments_base64.indexOf(",")+1);
alert(attachments_base64_replaced);
tinyMCE.triggerSave();
var body = $("#moj_tekst_editor").val();
var body_escape_double_qoute = body.replace(/"/g, '\\"');
//var body_escape_single_qoute = body_escape_double_qoute.replace(/'/g, "\\'");
var body_escape_forward_slash = body_escape_double_qoute.replace("/", "\\/");
var body_escape_forward_slash = body_escape_double_qoute.replace("/", "\\/");
alert(body_escape_forward_slash);
var email = '{"message":{"subject": "'+subject+'","body": {"contentType": "HTML","content": "'+body_escape_forward_slash+'"},"toRecipients": [{"emailAddress": {"address": "'+recipient+'"}}],"ccRecipients": [{"emailAddress": {"address": "'+carbon_copies+'"}}],"bccRecipients": [{"emailAddress": {"address": "'+blind_carbon_copies+'"}}],"attachments":[{"#odata.type":"#Microsoft.OutlookServices.FileAttachment","name":"'+filename_attachment+'","contentBytes":"'+attachments_base64_replaced+'"}]}, "saveToSentItems": "true"}'
console.log(email);
// Send Email
client
.api('/me/sendMail')
.header('Content-Type', "application/json")
.post(email, (err, res) => {
if (err) {
callback(null, err);
} else {
callback(res.value);
}
});
} else {
var error = { responseText: 'Could not retrieve access token' };
callback(null, error);
}
});
}
What do I need to do to be able to send email to more than one ccRecipient and bccRecipient? When I add more than one cc recipient message always comes to last one.
Thanks in advance!!

I found I can send emails to multiple toRecipients or ccRecipients by formatting the emailAddress in the following way:
{
"emailAddress": {
"address": "cc1#email.com"
}
},
{
"emailAddress": {
"address": "cc2#email.com"
}
}
Full request body looks like this:
{
"message": {
"subject": "Meet for lunch?",
"body": {
"contentType": "Text",
"content": "The new cafeteria is open."
},
"toRecipients": [
{
"emailAddress": {
"address": "address1#email.com"
}
},
{
"emailAddress": {
"address": "address2#email.com"
}
}
],
"ccRecipients": [
{
"emailAddress": {
"address": "cc1#email.com"
}
},
{
"emailAddress": {
"address": "cc2#email.com"
}
}
]
},
"saveToSentItems": "true"
}

Related

How to Send Hyperlinked text from Google sheet to Slack?

I want to send a hyperlinked text from Google sheet to Slack, for that, I have been able to develop this code using an online resource:
function sendNotificationtoSlack() {
var fileLink = SpreadsheetApp.getActiveSheet().getRange(5,2).getValue();
var url = 'https://hooks.slack.com/XXXXX'
var payload ={
text: fileLink
}
var headers = {
'Content-type':'application/json'
}
var options = {
headers:headers,
method:'POST',
payload:JSON.stringify(payload)
}
UrlFetchApp.fetch(url,options) }
The hyperlinked text in the sheet looks like this:
And in slack it comes in just plain text and is unclickable like this:
This source might be of any help. Can you guide me on how to send hyperlinked text in slack, so that it is clickable in the slack channel? Please let me know if you have any questions. Thank you
I found a way to attach the link to the text while sending it to slack, here is the workaround:
function sendNotificationtoSlack() {
var fileName = SpreadsheetApp.getActiveSheet().getRange(5,2).getValue();
var url = 'https://hooks.slack.com/XXXXX'
var payload = {
text: 'Someone *Updated* the Sheet! <' + 'TextLink' +"|"+fileName+">"
}
var headers = {
'Content-type':'application/json'
}
var options = {
headers:headers,
method:'POST',
payload:JSON.stringify(payload)
}
UrlFetchApp.fetch(url,options)
}
This will send text with a URL attached with it
You can add hyperlink via attachment with this syntax <url|text>
Try this way (and adapt to your speadsheet)
function slack() {
let message = {
"blocks": [
{
"type": "section",
"text": {
"type": "mrkdwn",
"text": "my question"
}
}
],
"attachments": [
{
"blocks": [
{
"type": "section",
"text": {
"type": "mrkdwn",
"text": "<https://stackoverflow.com/questions/73218375/how-to-send-hyperlinked-text-from-google-sheet-to-slack|How to Send Hyperlinked text from Google sheet to Slack?"
}
}
]
}
]
};
const webhook = ""; //Paste your webhook URL here
sendSlackAlert(webhook, message)
}
function sendSlackAlert(webhook, payload) {
var options = {
"method": "post",
"contentType": "application/json",
"muteHttpExceptions": true,
"payload": JSON.stringify(payload)
};
try {
UrlFetchApp.fetch(webhook, options);
} catch (e) {
Logger.log(e);
}
}

Status code error while posting json data using google script

I was writing an app script to send an sms. In the sms api document section, it's written that with the following, sms can be sent:
POST http://clients.muthofun.net/api/v3/sendsms/json
Host: http://clients.muthofun.net
Content-Type: application/json
Accept: */*
{
"authentication":{
"username":"test",
"password":"test"
},
"messages":[
{
"sender":"044XXXXXXXX",
"text":"Hello",
"recipients":[
{
"gsm":"88017XXXXXXXX"
}
]
}
]
}
So I write the following script code,
modified as #Tanaike said
function myFunction() {
var _auth = {
"username": "*****",
"password": "*****"
};
var rec = {
"gsm": "xxxxxxxxxxx"
};
var msg = {
"sender": "xxxxxxxxxxx",
"text": "Hello",
"recipients": [rec]
};
var payload = {
"authentication": _auth,
"messages": [msg]
};
_payload = JSON.stringify(payload)
var options = {
'method' : 'POST',
'contentType': 'application/json',
"accept": "*/*",
"payload": _payload
};
var url = "http://clients.muthofun.net/api/v3/sendsms/json";
var response = UrlFetchApp.fetch(url, options);
Logger.log(response);
}
But the actual response is:
{
"results":[
{
"status":"0",
"messageid":"10210011344550330860",
"destination":"88017XXXXXXXX"
}
]
}
but from the Logger function I get the following response
{
"results":[
{
"status":"-5",
"messageid":"",
"destination":"8801552555645"
}
]
}
Is it because I missed out a square bracket in the recipients and messages section? Or I am doing something wrong while sending the post request to the url?
How about this modification? In your sample request body, messages is as follows.
{
"authentication": {
"username": "test",
"password": "test"
},
"messages": [
{
"sender": "044XXXXXXXX",
"text": "Hello",
"recipients": [
{
"gsm": "88017XXXXXXXX"
}
]
}
]
}
In your script, it is as follows.
{
"authentication": {
"username": "*****",
"password": "*****"
},
"messages": {
"sender": "xxxxxxxxxxx",
"text": "Hello",
"recipients": {
"gsm": "xxxxxxxxxxx"
}
}
}
In your script, the values of messages and recipients are not array. So how about this modification?
Modified script :
From :
var msg = {
"sender": "xxxxxxxxxxx",
"text": "Hello",
"recipients": rec
};
var payload = {
"authentication": _auth,
"messages": msg
};
To :
var msg = {
"sender": "xxxxxxxxxxx",
"text": "Hello",
"recipients": [rec] // Modified
};
var payload = {
"authentication": _auth,
"messages": [msg] // Modified
};
And accept should be included in headers.
I'm not sure whether this modification resolves your issue, because I cannot test it. If this was not useful for you, can you provide the detail situation of the error?
Edit :
In this modification, option was modified.
var options = {
"method" : "POST",
"contentType": "application/json",
"headers": {"accept": "*/*"}, // Modified
"payload": payload // Modified
};
Rather than doing json request I made a http request to send sms.
Here is the code:
function myFunction() {
var username = "*****";
var password = "****";
var msg = "Harry kane didn't score!!! why!!!! why on August!!! :'(";
var phone = "xxxxxxxxxxx";
var url = "http://clients.muthofun.com:8901/esmsgw/sendsms.jsp?user="+username+"&password="+password+"&mobiles="+phone+"&sms="+msg;
Logger.log(url)
var response = UrlFetchApp.fetch(url);
Logger.log(response);
}

How to POST Geolocation values to a Sharepoint List Field with Rest API?

I need to post two values Caption and Location, later being a GeoLocation field in Sharepoint list. I am using the following JSON:
{"__metadata": { "type": "SP.ListItem" }, "Caption": "Testing", "Location": "POINT (78.4 17.4)"}
But it's not working. Shows the following error:
Cannot deserialize data for type Microsoft.SharePoint.SPFieldGeolocationValue
I am doing this from Xcode.
SharePoint REST service expects SP.FieldGeolocationValue to be specified in the following format:
{
"__metadata": {
"type": "SP.FieldGeolocationValue"
},
"Altitude": <val>,
"Latitude": <val>,
"Longitude": <val>,
"Measure": <val>
}
JavaScript example
The example demonstrates how to create list item in Contacts list and set Geolocation value for Location field:
function createContact(name,location){
var listTitle = 'Contacts';
var url = _spPageContextInfo.webAbsoluteUrl + "/_api/web/lists/getByTitle('" + listTitle + "')/items";
var payload = {
"__metadata": { "type": "SP.ListItem" },
"Title": name,
"Location": {
"__metadata": {"type": "SP.FieldGeolocationValue"},
"Latitude": location[0],
"Longitude": location[1],
}
};
return executeJson(url,'POST',null,payload);
}
createContact("Work Address", [60.2872339,24.8516785])
.done(function(data)
{
console.log('Contact has been created');
})
.fail(function(error){
console.log('An error occured while creating contact');
});
where
function executeJson(url,method,headers,payload)
{
method = method || 'GET';
headers = headers || {};
headers["Accept"] = "application/json;odata=verbose";
if(method == "POST") {
headers["X-RequestDigest"] = $("#__REQUESTDIGEST").val();
}
var ajaxOptions =
{
url: url,
type: method,
contentType: "application/json;odata=verbose",
headers: headers
};
if (typeof payload != 'undefined') {
ajaxOptions.data = JSON.stringify(payload);
}
return $.ajax(ajaxOptions);
}

Use Mandrill API in Google Apps Script

I want to use mandrill email sending api in my google apps script. In google script I have to use JSON code but I am not getting how I will use it. I am very new in Google apps script.
var m = new mandrill.Mandrill('XXXXXXXXXXX');
var from_email = "user4#gmail.com";
var to = '[
{
"email": "recipient.email#example.com",
"name": "Recipient Name"
}
],';
// create a variable for the API call parameters
var params = {
"message": {
"from_email":from_email,
"to":[{"email":to}],
"subject": "Sending a text email from the Mandrill API",
"text": "I'm learning the Mandrill API at Codecademy, it's very difficult."
}
};
function sendTheMail() {
// Send the email!
alert('this is a mail script');
m.messages.send(params, function(res) {
log(res);
}, function(err) {
log(err);
});
}
I am not getting how to use this code in Google Apps Script.
You'd need to use the urlfetchapp.
var url = "https://mandrillapp.com/api/1.0/messages/send.json";
var your_key = "xxxxxxxxxxxxx";
var from_email = "user4#gmail.com";
var to = [{
"email": "recipient.email#example.com",
"name": "Recipient Name"
}];
var params = {
"key": your_key,
"message": {
"from_email":from_email,
"to":[{"email":to}],
"subject": "Sending a text email from the Mandrill API",
"text": "I'm learning the Mandrill API at Codecademy, it's very difficult."
}
};
var payload = JSON.stringify(params);
var options = {
'method': 'post',
'payload': payload,
'contentType' : 'application/json'
};
var response = UrlFetchApp.fetch(url, options);
Haven't tested this code, but should be something like that.
I paste sample code example to send email by Mandrill with attachment file from Google Drive.
function sendEmail() {
var MANDRILL_API_KEY = "<<your key here>>";
var files = [
"<<Google Drive File ID 1>>",
"<<Google Drive File ID 2>>",
"<<Google Drive File ID 3>>"
];
var recipients = [
{
"email": "ctrlq+to#labnol.org",
"name": "Amit Agarwal",
"type": "to"
}, {
"email": "ctrlq+cc#labnol.org",
"type": "cc"
}, {
"email": "ctrlq+bcc#gmail.com",
"type": "bcc"
}
];
var attachments = [];
for (var f in files) {
var file = DriveApp.getFileById(files[f]);
attachments.push({
"type": file.getMimeType(),
"name": file.getName(),
"content": Utilities.base64Encode(file.getBlob().getBytes())
});
}
var params = {
"key": MANDRILL_API_KEY,
"message": {
"from_email": "<<Sender's Email Address>>",
"from_name": "<<Sender Name>>",
"to": recipients,
"attachments": attachments,
"headers": {
"Reply-To": "reply#example.com"
},
"subject": "Enter email subject",
"text" : "Enter email body in plain text",
"html" : "Enter HTML content with <b>tags</b>"
}
};
var response = UrlFetchApp.fetch(
"https://mandrillapp.com/api/1.0/messages/send.json", {
'method': 'POST',
'payload': JSON.stringify(params),
'contentType': 'application/json'
});
Logger.log(response.getContentText());
}
Sample code is extracted from website ctrlq of Amit Agarwal

How to receive a json string after a jquery post in WebMatrix?

If I have the following post call:
$('#json_form').submit(function (event) {
event.preventDefault();
var url = $(this).attr('action');
var datos = {
"uno": "lalala",
"dos": "jojojo"
}
var data = JSON.stringify(datos);
$.post(url, data, function (resultado) {
$('#posted_values').html(resultado);
});
});
How can I receive and process the json object in a cshtml file? I mean what I put in Decode call:
if (IsPost)
{
var json_object = Json.Decode(Request???);
}
Edited to complete the answer of #MikeBrind, to help others with the same problem.
Example of using decode for a more complex json object.
$('#json_form').submit(function (event) {
event.preventDefault();
var url = $(this).attr('action');
var datos = {
"firstName": "John",
"lastName": "Smith",
"age": 25,
"address": {
"streetAddress": "21 2nd Street",
"city": "New York",
"state": "NY",
"postalCode": 10021
},
"phoneNumber": [
{
"type": "home",
"number": "212 555-1234"
},
{
"type": "fax",
"number": "646 555-4567"
}
]
}
var data = JSON.stringify(datos);
$.post(url, {"person": data}, function (resultado) {
$('#posted_values').html(resultado);
});
});
Receiving and using:
#{
dynamic json_object;
if (IsPost)
{
json_object = Json.Decode(Request["person"]);
#json_object.firstName<br/>
#json_object.lastName<br/>
#json_object.address.city<br/>
#json_object.address.postalCode<br/>
foreach (dynamic phone in json_object.phoneNumber)
{
#phone.type<br/>
#phone.number
}
}
}
Don't JSON.stringify the data if it is just key/value pairs like this. Do a form post:
$('#json_form').submit(function (event) {
event.preventDefault();
var url = $(this).attr('action');
var datos = {
"uno": "lalala",
"dos": "jojojo"
}
//var data = JSON.stringify(datos); no need for this
$.post(url, datos, function (resultado) {
$('#posted_values').html(resultado);
});
});
Then the values are available from Request["uno"] and Request["dos"]
If you ever do need to use JSON.stringify (which you would for more complex data structures), the JSON is transmitted in the Request body, so you need to extract it from Request.InputStream:
var reader = new StreamReader(Request.InputStream);
var json = reader.ReadToEnd();