I want to create a draft Gmail email message using Google Apps Script, like in the following example taken from Mogsdad's accepted answer to the Create draft mail using Google apps script question:
function createDraft() {
var forScope = GmailApp.getInboxUnreadCount(); // needed for auth scope
var raw =
'Subject: testing Draft\n' +
//'To: test#test.com\n' +
'Content-Type: multipart/alternative; boundary=1234567890123456789012345678\n' +
'testing Draft msg\n' +
'--1234567890123456789012345678--\n';
var draftBody = Utilities.base64Encode(raw);
var params = {method:"post",
contentType: "application/json",
headers: {"Authorization": "Bearer " + ScriptApp.getOAuthToken()},
muteHttpExceptions:true,
payload:JSON.stringify({
"message": {
"raw": draftBody
}
})
};
var resp = UrlFetchApp.fetch("https://www.googleapis.com/gmail/v1/users/me/drafts", params);
Logger.log(resp.getContentText());
It works great, BUT I want to embedd some image in the message body, without linking to external URL, so it always shows up, it's not blocked by some email clients, including Gmail. How to do that?
Related
I'm trying to use the ebay REST-API for the first. I am simply trying to generate an access_token using the client credentials grant-request. I followed the instructions here https://developer.ebay.com/api-docs/static/oauth-client-credentials-grant.html
HTTP method: POST
URL (Sandbox): https://api.sandbox.ebay.com/identity/v1/oauth2/token
HTTP headers:
Content-Type = application/x-www-form-urlencoded
Authorization = Basic <B64-encoded_oauth_credentials>
Request body (wrapped for readability):
grant_type=client_credentials&
redirect_uri=<RuName-value>&
scope=https://api.ebay.com/oauth/api_scope
I'm getting this error: {'error': 'invalid_client', 'error_description': 'client authentication failed'} and my code looks like this:
path = 'https://api.sandbox.ebay.com/'
app_json = 'application/json'
headers = {
'Content-Type': 'application/x-www-form-urlencoded',
'Authorization': base64.b64encode(b'Basic CLIENT_ID:CLIENT_SECRET')
}
payload = 'grant_type=client_credentials&redirect_uri=Searchez&scope=https://api.ebay.com/oauth/api_scope'
def get_oath_token():
url = 'https://api.sandbox.ebay.com/identity/v1/oauth2/token'
r = requests.post(url, headers=headers, data=payload)
print(r.json())
get_oath_token()
What do I have configured incorrectly? Thanks.
You're base64encoding "Basic " and shouldn't be.
The doc says just encode your Client ID + ":" + Client Secret, and leave the word "Basic" and the space that follows it alone.
In your code, i can see sandbox endpoint URI but in the request body scope, you have used production URL, instead of sandbox
I am using a service account in google apps script so i can not use the normal google apps script api.
So i use the drive rest api for creating, moving, copy etc. but i am able to upload a file with the rest api. It uploads a file but it is without content or with wrong content.
This is my code:
var contentType = data.substring(5, data.indexOf(';')),
bytes = Utilities.base64Decode(data.substr(data.indexOf('base64,') + 7)),
blob = Utilities.newBlob(bytes, contentType, file);
var service = getService();
if (service.hasAccess()) {
var url = 'https://www.googleapis.com/upload/drive/v3/files?uploadType=media';
var data = {
name: name,
mimeType: "application/pdf",
parents: [parent]
};
var options = {
method: 'post',
contentType: 'application/json',
body: blob ,
payload: JSON.stringify(data),
muteHttpExceptions: true,
headers: {
Authorization: 'Bearer ' + service.getAccessToken()
}
};
var response = UrlFetchApp.fetch(url, options);
var result = JSON.stringify(response.getContentText());
Logger.log(JSON.stringify(result, null, 2));
return result["id"];
} else {
Logger.log(service.getLastError());
}
Thanks
When uploading files using Drive API, you need to use the files.create method. You can see the javascript code reference in Basic uploads where it is used. Also note that the App Script uploading files uses the Drive v2 version of files.insert instead of files.create.
Hi I'm trying to send a POST call to the SparkPost API in a JavaScript web app. It works fine with curl and Postman, but as soon as I try sending from my localhost site I get a 401 Unauthorized error.
My current code looks like the below, but I've tried fetch as well with the same results.
sendEmail(subject, data) {
let textbody = "blah blah blah";
const url = "https://api.sparkpost.com/api/v1/transmissions";
const fetchbody = {
content: {
from: "sandbox#sparkpostbox.com",
subject: subject,
text: textbody
},
recipients: [{address: "myaddress#gmail.com"}]
};
var xhr = new XMLHttpRequest();
xhr.withCredentials = true;
xhr.addEventListener("readystatechange", function () {
if (this.readyState === 4) {
console.log(this.responseText);
}
});
xhr.open("POST", url);
xhr.setRequestHeader("content-type", "application/json");
xhr.setRequestHeader("accept", "application/json");
xhr.setRequestHeader("authorization", creds);
xhr.setRequestHeader("cache-control", "no-cache");
xhr.send(JSON.stringify(fetchbody));
}
Is there something wrong with my credentials setup here? Note that creds is set to my secret API key string.
Figured it out after chatting with the Sparkpost devs a bit - the service only allows "strict CORS" i.e. requests from server-side, and I was sending the request from client-side code.
I think TFS RESTful api has a bug. I am trying to access it using an Angular web app. Our TFS server is corporate internal. Here is my code:
var path = 'http://tfs.mycompany.com/tfs/mycompany/_apis/wit/queries?$depth=1&$expand=all&api-version=2.2';
var config = { withCredentials: true };
$http.get(path, config)
.then(function (response) {
$scope.resultList = response.data.d.results || [ response.data.d ];
$scope.message = 'Found ' + $scope.resultList.length + ' item' + ($scope.resultList.length == 1 ? '':'s');
}, function (response) {
$scope.resultList = [];
$scope.message = 'Error ' + response.status + ' ' + JSON.stringify(response.data);
});
The request goes to the server, and the server responds with OK 200. However, the browser (Chrome) blocks the data, and tells me:
A wildcard '*' cannot be used in the 'Access-Control-Allow-Origin' header
when the credentials flag is true. Origin 'http://localhost' is therefore
not allowed access. The credentials mode of an XMLHttpRequest is controlled
by the withCredentials attribute.
The request headers have Origin:http://localhost
The response headers have Access-Control-Allow-Origin:*
Is there any way for me to tell TFS to not return * in the Access-Control-Allow-Origin? This seems like a serious bug in TFS, which renders the RESTful api practically useless for web apps!
You may check Cross-origin resource sharing (CORS) example below to add Authorization in your code:
$( document ).ready(function() {
$.ajax({
url: 'https://fabrikam.visualstudio.com/defaultcollection/_apis/projects?api-version=1.0',
dataType: 'json',
headers: {
'Authorization': 'Basic ' + btoa("" + ":" + myPatToken)
}
}).done(function( results ) {
console.log( results.value[0].id + " " + results.value[0].name );
});
});
Also, check this case to see whether it is helpful:
AJAX cross domain issue with Visual Studio Online REST API
I am accessing a list through SharePoint 2013 App using REST, below is code snippet:
var executor = new SP.RequestExecutor(appweburl);
executor.executeAsync(
{
url: appweburl +
"/_api/SP.AppContextSite(#hostweburl)/Web/lists/getbytitle('SomeListName')/items?" +
"#hostweburl='" +
hostweburl + "'",
method: "GET",
headers: { "Accept": "application/json; odata=verbose" },
success: successHandler,
error: errorHandler
}
);
when i am debugging it, getting the complete URL from URL tag, but when i am going to access it through browser, it shows me message like "Sorry, this site hasn't been shared with you".
Why is this so happen while i have the full control over site collection.
Is there any configuration which we have to be made in APP?
Thanks.