My objective is to use the upload attachment functionality of the Gmail API. The uploaded file is to be processed within my Gmail add-on. I found the following POST request in this link.
POST https://www.googleapis.com/upload/gmail/v1/users/userId/messages/send?uploadType=media
Here is my try so far:
function testPOST() {
Logger.log('Testing of POST in Apps script');
// var url = ScriptApp.getService().getUrl();
var url = "https://www.googleapis.com/upload/gmail/v1/users/userId/messages/send"
Logger.log('URL:'+url);
var options =
{
"method" : "POST",
"uploadType" : "media"
};
// Trying to fetch the file
var result = UrlFetchApp.fetch(url, options);
Logger.log('Response code: ' + result.getResponseCode());
// maybe I need to use some function in 'Gmail.Users.*'
}
Related
I have a google script that sends an email with a Word doc as an attachment. It used to work until google deprecated OAuth 1.0
This is the line that's failing:
var doc = UrlFetchApp.fetch(url+'download/documents/Export?exportFormat=doc&format=doc&id='+ copyId, googleOAuth_('docs',url)).getBlob();
If I remove the second parameter, i.e. function call to OAuth, it should work? Why do I need to authenticate? It should be able to fetch the document using an ID from google drive. It appears to work (because I don't see any errors), however, when I get an email there is a corrupt word doc attachment.
So, I tried implementing OAuth 2.0. But I'm not getting anywhere. Here's my code:
function getDriveService() {
return OAuth2.createService('drive')
.setAuthorizationBaseUrl('https://accounts.google.com/o/oauth2/auth')
.setTokenUrl('https://accounts.google.com/o/oauth2/token')
.setClientId(CLIENT_ID)
.setClientSecret(CLIENT_SECRET)
.setCallbackFunction('authCallback')
.setPropertyStore(PropertiesService.getUserProperties())
.setScope('https://www.googleapis.com/auth/drive')
.setParam('login_hint', Session.getActiveUser().getEmail())
.setParam('access_type', 'offline');
//.setParam('approval_prompt', 'force');
}
function authCallback(request) {
var driveService = getDriveService();
var isAuthorized = driveService.handleCallback(request);
if (isAuthorized) {
return HtmlService.createHtmlOutput('Success! You can close this tab.');
} else {
return HtmlService.createHtmlOutput('Denied. You can close this tab');
}
}
var oauth2Service = getDriveService();
var token = oauth2Service.getAccessToken();
var parameters = { method : 'get',
headers : {'Authorization': 'Bearer '+ token}};
var options =
{
"method" : "get"
};
var resp = UrlFetchApp.fetch('https://docs.google.com/feeds/download/documents/Export?exportFormat=doc&format=doc&id='+ copyId, parameters);
doc = resp.getBlob();
I'm getting a generic error [Access not granted or expired]. All I want is to be able to send an email with an attachment that is a document (format doc or docx) stored from my Google drive. Seems impossible! I'm able to attach this doc as a pdf but NOT a Microsoft document.
Any help will be greatly appreciated!
https://github.com/googlesamples/apps-script-oauth2 - look at setup
...
Have you added OAuth 2.0 in the libraries?
Resources -> Libraries -> then add 'MswhXl8fVhTFUH_Q3UOJbXvxhMjh3Sh48'
I'm trying desperately to create a Firefox add-on that posts a file with the field name "Filedata" to a particular PHP script which will only work if it sees a JPG in the $_FILE["Filedata"] variable.
I put a web form with a file browser into panel.html, then I take the image and turn it into a canvas which I turn into a blob and send to main.js. I would be happy to send the file directly from panel.js, but nothing at all happens (no error message either) when I attempt to so.
In main.js, I have this code but I get an error message that FormData doesn't exist in main.js. What to do?
function ajupload(mydata) {
var fd = new FormData();
fd.append("Filedata", mydata);
const {XMLHttpRequest} = require("sdk/net/xhr");
var myrequest = new XMLHttpRequest();
myrequest.open('POST', 'MYSITE/image.php?action=upload');myrequest.setRequestHeader("Content-type","application/x-www-form-urlencoded");
myrequest.upload.addEventListener("progress", function(e) {
var percentage = Math.round((e.loaded * 100) / e.total);
}, false);
myrequest.onreadystatechange=function()
{
if (myrequest.readyState==4 && myrequest.status==200)
{
console.log("Response" + myrequest.responseText);
}
}
myrequest.send(fd);
}
As the title suggests, my goal here is to be able to send a tweet from a script.gs. The tweet would be posted to my feed, ideally without me having to visit the Twitter website.
I wrote two main functions to attempt this:
script.gs
//post tweet
function oAuth() {
var CONSUMER_KEY = "**********************";
var CONSUMER_SECRET = "*************************************************";
ScriptProperties.setProperty("TWITTER_CONSUMER_KEY", CONSUMER_KEY);
ScriptProperties.setProperty("TWITTER_CONSUMER_SECRET", CONSUMER_SECRET);
var oauthConfig = UrlFetchApp.addOAuthService("twitter");
oauthConfig.setAccessTokenUrl("https://api.twitter.com/oauth/access_token");
oauthConfig.setRequestTokenUrl("https://api.twitter.com/oauth/request_token");
oauthConfig.setAuthorizationUrl("https://api.twitter.com/oauth/authorize");
oauthConfig.setConsumerKey(ScriptProperties.getProperty("TWITTER_CONSUMER_KEY"));
oauthConfig.setConsumerSecret(ScriptProperties.getProperty("TWITTER_CONSUMER_SECRET"));
var options = {muteHttpExceptions: true,oAuthServiceName:'twitter',oAuthUseToken:'always'}
var url = "https://api.twitter.com/1.1/statuses/user_timeline.json";
var response = UrlFetchApp.fetch(url, options).getContentText();
Logger.log(response);
}
function postTweet() {
oAuth();
Logger.log('oAuth complete');
var status = "Tweet";
var Roptions = {
method: "post",
oAuthServiceName: "twitter",
oAuthUseToken: "always",
status: status
};
var url = "https://api.twitter.com/1.1/statuses/update.json";
Logger.log('begin post');
var request = UrlFetchApp.fetch(url, Roptions); //the trouble line. Execution stops.
Logger.log('post complete');
}
After about a day of relentless hacking, I was able to get the first function, oAuth() to work. That logs, well, my user data. However, for the life of me, I cannot figure out what is holding up request. I do get this error: Request failed for returned code 403. Truncated server response: {"errors":[{"message":"SSL is required","code":92}]}. Googling this didn't turn up much. I'm guessing that the issue is somewhere in Roptions. Any help would be appreciated, and I can try to provide further clarification if needed.
Eureka! Here's the solution. The irony is that I had had something like this before, but had dismissed it. Turns out https was my biggest problem. I'll feast on humble pie tonight.
script to send tweet
//post tweet
function oAuth() {
var CONSUMER_KEY = "*************************";
var CONSUMER_SECRET = "**************************************************";
ScriptProperties.setProperty("TWITTER_CONSUMER_KEY", CONSUMER_KEY);
ScriptProperties.setProperty("TWITTER_CONSUMER_SECRET", CONSUMER_SECRET);
var oauthConfig = UrlFetchApp.addOAuthService("twitter");
oauthConfig.setAccessTokenUrl("https://api.twitter.com/oauth/access_token");
oauthConfig.setRequestTokenUrl("https://api.twitter.com/oauth/request_token");
oauthConfig.setAuthorizationUrl("https://api.twitter.com/oauth/authenticate");
oauthConfig.setConsumerKey(ScriptProperties.getProperty("TWITTER_CONSUMER_KEY"));
oauthConfig.setConsumerSecret(ScriptProperties.getProperty("TWITTER_CONSUMER_SECRET"));
var options = {muteHttpExceptions: true,oAuthServiceName:'twitter',oAuthUseToken:'always'}
var url = "https://api.twitter.com/1.1/statuses/user_timeline.json";
var response = UrlFetchApp.fetch(url, options).getContentText();
Logger.log(response);
}
function postTweet() {
oAuth();
Logger.log('oAuth complete');
var status='Test tweet';
var options = {
"method": "post",
"oAuthServiceName": "twitter",
"oAuthUseToken": "always",
"payload":{"status":status}
};
var url = "https://api.twitter.com/1.1/statuses/update.json";
Logger.log('begin post');
var request = UrlFetchApp.fetch(url, options);
Logger.log('post complete');
}
When you register your Twitter app, you have to check the option Allow this application to be used to Sign in with Twitter. This prevents continual Authorize popups. Also, the tweet text CANNOT contain single quotes (').
#J148, oauthConfig depricated and you can't use it anymore;
Now for twitter you have to use OAuth1 for Apps Script. Migration docs:
https://developers.google.com/apps-script/migration/oauth-config?utm_campaign=oauth-appsscript-315&utm_source=gadbc&utm_medium=blog
Sample:
https://github.com/googlesamples/apps-script-oauth1/blob/master/samples/Twitter.gs
To make sample working you have to:
Add "OAuth1 for Apps Script library" to your script project
Declare some stub "Callback URL" in the twitter app's settings
I had a Google Apps Script to take appointments from my Google Calendar, copy them into a Google Sheet, convert it to XLS and email it. It was working fine until this week.
The initial problem was a 302 error, probably caused by the new version of Sheets. This has been discussed here: Export (or print) with a google script new version of google spreadsheets to pdf file, using pdf options
I got the new location of the file by muting the HTTP exceptions and adjusting the URL accordingly. I also updated the OAuth scope to https://docs.google.com/feeds/ as suggested.
The program is failing with an "OAuth error" message. When muteHttpExceptions is set to true, the message is "Failed to authenticate to service: google".
I guess this is a scope problem but I really can't see what I've done wrong. Naturally, I've tried a few other possibilities without luck.
I've included the code below. Commented code is the instruction that worked until this week.
function getSSAsExcel(ssID)
{
var format = "xls";
//var scope = "https://spreadsheets.google.com/feeds/";
var scope = "https://docs.google.com/feeds/";
var oauthConfig = UrlFetchApp.addOAuthService("google");
oauthConfig.setAccessTokenUrl("https://www.google.com/accounts/OAuthGetAccessToken");
oauthConfig.setRequestTokenUrl("https://www.google.com/accounts/OAuthGetRequestToken?scope=" + scope);
oauthConfig.setAuthorizationUrl("https://www.google.com/accounts/OAuthAuthorizeToken");
oauthConfig.setConsumerKey("anonymous");
oauthConfig.setConsumerSecret("anonymous");
var requestData = {
//"muteHttpExceptions": true,
"method": "GET",
"oAuthServiceName": "google",
"oAuthUseToken": "always"
};
//var url = "https://spreadsheets.google.com/feeds/download/spreadsheets/Export?key=" + ssID
var url = "https://docs.google.com/spreadsheets/d/" + ssID
+ "/feeds/download/spreadsheets/Export?"
+ "&size=A4" + "&portrait=true" +"&fitw=true" + "&exportFormat=" + format;
var result = UrlFetchApp.fetch(url , requestData);
var contents = result.getContent();
return contents;
}
Thanks for your help!
Instead of using OAuthConfig (which must be auth'ed in the Script Editor) you can pass an OAuth2 token instead, retrievable via ScriptApp.getOAuthToken().
The code snippet below uses the Advanced Drive service to get the export URL, but if you hand construct the URL you'll need to ensure that the Drive scope is still requested by your script (simply include a call to DriveApp.getRootFolder() somewhere in your script code).
function exportAsExcel(spreadsheetId) {
var file = Drive.Files.get(spreadsheetId);
var url = file.exportLinks[MimeType.MICROSOFT_EXCEL];
var token = ScriptApp.getOAuthToken();
var response = UrlFetchApp.fetch(url, {
headers: {
'Authorization': 'Bearer ' + token
}
});
return response.getBlob();
}
Hello guys I need help in auto login to youtube.com to upload videos "browser-based" (and later get them data to show in a site by api). So basicly I downloaded extension from here http://framework.zend.com/downloads/latest Zend Gdata. And make it work.
It works fine (demos/.../YouTubeVideoApp). But how can i do auto login to youtube without confirmation page ("grant access" \ "deny access")? Currently I use developer key to work with youtube api.
The message of confirmation is
An anonymous application is requesting access to your Google Account for the product(s) listed below.
YouTube
If you grant access, you can revoke access at any time under 'My Account'. The anonymous application will not have access to your password or any other personal information from your Google Account. Learn more
This website has not registered with Google to establish a secure connection for authorization requests. We recommend that you continue the process only if you trust the following destination:
http://somedomain/operations.php
In general I need create connection to youtube (by api) and upload there (using my own account) video without any popups and confirmation pages.
i think all you need is to get a access token and set it to a session value "$_SESSION['sessionToken']". Combination of javascript and PHP will need to do this. previously i always have to grant access or deny it while using Picasa web API but after changes that i described below, grant or access page is no longer needed.
I have not integrated youtube with zend Gdata but have integrated Picasa web Albums using it
make a login using javascript popup and get a token for a needed scope. below is a javascript code. change your scope to youtube data as in this scope for picasa is used.. click function "picasa" on your button onclick.
var OAUTHURL = 'https://accounts.google.com/o/oauth2/auth?';
var VALIDURL = 'https://www.googleapis.com/oauth2/v1/tokeninfo?access_token=';
var SCOPE = 'https://picasaweb.google.com/data';
var CLIENTID = YOUR_CLIENT_ID;
var REDIRECT = 'http://localhost/YOUR_REDIRECT_URL'
var LOGOUT = 'http://accounts.google.com/Logout';
var TYPE = 'token';
var _url = OAUTHURL + 'scope=' + SCOPE + '&client_id=' + CLIENTID + '&redirect_uri=' + REDIRECT + '&response_type=' + TYPE;
var acToken;
var tokenType;
var expiresIn;
var user;
var loggedIn = false;
function picasa() {
var win = window.open(_url, "windowname1", 'width=800, height=600');
var pollTimer = window.setInterval(function() {
console.log(win);
console.log(win.document);
console.log(win.document.URL);
if (win.document.URL.indexOf(REDIRECT) != -1) {
window.clearInterval(pollTimer);
var url = win.document.URL;
acToken = gup(url, 'access_token');
tokenType = gup(url, 'token_type');
expiresIn = gup(url, 'expires_in');
win.close();
validateToken(acToken);
}
}, 500);
}
function validateToken(token) {
$.ajax({
url: VALIDURL + token,
data: null,
success: function(responseText){
//alert(responseText.toSource());
getPicasaAlbums(token);
loggedIn = true;
},
dataType: "jsonp"
});
}
function getPicasaAlbums(token) {
$.ajax({
url: site_url+"ajaxs/getAlbums/picasa/"+token,
data: null,
success: function(response) {
alert("success");
}
});
}
//credits: http://www.netlobo.com/url_query_string_javascript.html
function gup(url, name) {
name = name.replace(/[\[]/,"\\\[").replace(/[\]]/,"\\\]");
var regexS = "[\\#&]"+name+"=([^&#]*)";
var regex = new RegExp( regexS );
var results = regex.exec( url );
if( results == null )
return "";
else
return results[1];
}
Here i am making a ajax call in function "getPicasaAlbums" and setting token to a $_session there and after it i am able to get a album listing using zend queries. here is a some code of php file that i am calling using ajax in function "getPicasaAlbums".
function getAlbums($imported_from = '',$token = '') {
//echo $imported_from; //picasa
//echo $token;
$_SESSION['sessionToken'] = $token;// set sessionToken
$client = getAuthSubHttpClient();
$user = "default";
$photos = new Zend_Gdata_Photos($client);
$query = new Zend_Gdata_Photos_UserQuery();
$query->setUser($user);
$userFeed = $photos->getUserFeed(null, $query);
echo "<pre>";print_r($userFeed);echo "</pre>";exit;
}
i think this will help you a little in your task. relpace above "getAlbums" function's code with your youtube zend data code to retrieve data.
good example & referene of a login popup is here
http://www.gethugames.in/blog/2012/04/authentication-and-authorization-for-google-apis-in-javascript-popup-window-tutorial.html