Email Settings APIs Authentication - email

I would like to use the Email Settings API with Apps Script to manage all users signatures on a Google Site. I have used Documents Data APIs before with 2-legged OAuth and it worked just fine. I am currently stuck on the authentication step for Email Settings API.
Code example:
// Setup OAuthServiceConfig
var oAuthConfig = UrlFetchApp.addOAuthService("signature");
oAuthConfig.setAccessTokenUrl("https://www.google.com/accounts/OAuthGetAccessToken");
oAuthConfig.setRequestTokenUrl("https://www.google.com/accounts/OAuthGetRequestToken");
//I left scope empty to gain access to all APIs would this scope work scope=https://apps-apis.google.com/a/feeds/emailsettings/2.0/
oAuthConfig.setAuthorizationUrl("https://www.google.com/accounts/OAuthAuthorizeToken");
oAuthConfig.setConsumerKey("domain.com");
oAuthConfig.setConsumerSecret("consumerSecret");
// Setup optional parameters to point request at OAuthConfigService. The "signature"
// value matches the argument to "addOAuthService" above.
var options =
{
"method" : method,
"oAuthServiceName" : "signature",
"oAuthUseToken" : "always"
};
var result = UrlFetchApp.fetch("https://apps-apis.google.com/a/feeds/emailsettings/2.0/"+domainName+"/"+userName+"/signature", options);
Logger.log(result);
I get this error: "Unexpected Error (line 37)" which is
var result = UrlFetchApp.fetch("https://apps-apis.google.com/a/feeds/emailsettings/2.0/"+domainName+"/"+userName+"/signature", options);
Any thoughts on what I am doing wrong?
Scopes are here: http://support.google.com/a/bin/answer.py?hl=en&answer=162105

Hope this will help you. This is an working example which will get the user's HTML signature or Update HTML signature
/*
----------------------------------------------------------------------------------
This function will update the HTML signature of a user.
Input will be jason data
To disable signature, pass an empty string as signature value
sample parameter
ob = {user='hps', signature='<b>Regards</b><br>Waqar'}
To disable signature
ob = {user='hps', signature=''}
----------------------------------------------------------------------------------
*/
function updateSignature(ob) {
//ob = {};
//ob.user = "hps";
//ob.signature = "<b>Regards</b><br>Waqar";
var base = 'https://apps-apis.google.com/a/feeds/emailsettings/2.0/';
var xmlRaw = '<?xml version="1.0" encoding="utf-8"?>'+
'<atom:entry xmlns:atom="http://www.w3.org/2005/Atom" xmlns:apps="http://schemas.google.com/apps/2006">'+
'<apps:property name="signature" value="'+htmlEncode(ob.signature)+'" />'+
'</atom:entry>';
var fetchArgs = googleOAuth_('emailSetting',base);
fetchArgs.method = 'PUT';
fetchArgs.payload = xmlRaw;
fetchArgs.contentType = 'application/atom+xml';
var domain = UserManager.getDomain();
var url = base+domain+'/'+ob.user+'/signature';
var urlFetch = UrlFetchApp.fetch(url, fetchArgs);
var status = urlFetch.getResponseCode();
return status;
}
//-----------------------------------------------------------------------------------------------------------
//This function will retreive Signature settings as json.
/*Sample returned object
{user=hps, signature=<b>Regards</b><br>Waqar}
*/
//-----------------------------------------------------------------------------------------------------------
function retrieveSignature(user) {
var user = 'hps';
var base = 'https://apps-apis.google.com/a/feeds/emailsettings/2.0/';
var fetchArgs = googleOAuth_('emailSetting',base);
fetchArgs.method = 'GET';
var domain = UserManager.getDomain();
var url = base+domain+'/'+user+'/signature?alt=json';
var urlFetch = UrlFetchApp.fetch(url, fetchArgs);
var jsonString = urlFetch.getContentText();
var jsonArray = Utilities.jsonParse(jsonString).entry.apps$property;
var ob = {};
ob.user = user;
for(var i in jsonArray){
ob[jsonArray[i].name] = jsonArray[i].value;
}
return ob;
}
//Google oAuthConfig..
function googleOAuth_(name,scope) {
var oAuthConfig = UrlFetchApp.addOAuthService(name);
oAuthConfig.setRequestTokenUrl("https://www.google.com/accounts/OAuthGetRequestToken?scope="+scope);
oAuthConfig.setAuthorizationUrl("https://www.google.com/accounts/OAuthAuthorizeToken");
oAuthConfig.setAccessTokenUrl("https://www.google.com/accounts/OAuthGetAccessToken");
oAuthConfig.setConsumerKey("anonymous");
oAuthConfig.setConsumerSecret("anonymous");
return {oAuthServiceName:name, oAuthUseToken:"always"};
}
//This function will escape '<' and '>' characters from a HTML string
function htmlEncode(str){
str = str.replace(/</g,'<');
return str.replace(/>/g,'>')
}

Related

using varialbles to call marker and update options wont work

i have to change my marker options by calling the variables assigned to them but heres the problem.
var CL1 = L.marker([-36.597889, -80.15625], {
divId: 1,
opacity: 1,
})
.addTo(map)
var id = 1; // this do not work
var clickedMarker = 'CL'+id; // this do not work
clickedMarker.setOpacity(.5); // this do not work
but this one work
CL1.setOpacity(.5); //working
why is that? the error I'm getting is Uncaught TypeError: clickedMarker.setOpacity is not a function
You are creating a String with var clickedMarker = 'CL'+id; and with that you will not able to access the variable CL1. You can use a list to map the variable name with the variable self.
var mapping = {};
var CL1 = L.marker([-36.597889, -80.15625], {
divId: 1,
opacity: 1,
})
.addTo(map)
mapping['CL1'] = CL1;
var id = 1;
var clickedMarkerId = 'CL'+id;
var clickedMarker = mapping[clickedMarkerId]; // get the marker variable over the String 'CL1'
clickedMarker.setOpacity(.5);

set values after sending mail

I want the script to send an email to those mail addresses where unchecked boxes are in the row - This works fine. But I want the value of the checkbox to be set “True” after the mails were sent.
My Problem is that I need the last for-loop to stop after all checkboxes are checked. In other words: The last loop has to stop when an empty cell appears.
First of all I manually trigger the script - later I will start it with the help of a button in the menu (function onOpen...)
Appreciate any help – thanks a lot!
Check out the sheet and the code below:
function sendmail() {
var ui = SpreadsheetApp.getUi();
var ss = SpreadsheetApp.getActiveSpreadsheet();
var s = ss.getSheetByName('Sheet1');
var r = s.getRange('C:C'); //Checkboxes
var v = r.getValues();
for(var i=v.length-1;i>=0;i--)
if(v[0,i]=='false') {
var range = ss.getRange("A1:D4");
var UserData = range.getValues();
var UserData = range.getValues();
var row = UserData[i];
var name = row[0];
var email = row[1];
MailApp.sendEmail(row[1], "Test", "Hello " + name + ", This is an email");
var response = ui.alert("mail was send to ", ui.ButtonSet.OK);
}
for (k=1; k < 20; k++) { //loop which has to stop
s.getRange(k, 3).setValue("True");
}
}
A couple of major changes in your script.
The condition for the loop is wrong. Change to:
for(var i=v.length-1;i>0;i--)
The UI response is missing the recipient name. Change to:
var response = ui.alert("mail was send to "+name, ui.ButtonSet.OK);
var UserData = range.getValues(); is declared twice: delete one row
Immediately after the UI alert (and still within the IF loop), add a line to update the checkbox: UserData[i][2] = true;
Simplify the updating of checkboxes.
Delete the existing lines:
for (k=1; k < 20; k++) {
s.getRange(k, 3).setValue("True");
}
Substitute:
range.setValues(UserData)
Revised Script
function sosendmail() {
var ui = SpreadsheetApp.getUi();
var ss = SpreadsheetApp.getActiveSpreadsheet();
var s = ss.getSheetByName('Sheet1');
var r = s.getRange('C:C'); //Checkboxes
var v = r.getValues();
for(var i=v.length-1;i>0;i--)
if(v[0,i]=='false') {
var range = ss.getRange("A1:D4");
var UserData = range.getValues();
var row = UserData[i];
var name = row[0];
var email = row[1];
// MailApp.sendEmail(row[1], "Test", "Hello " + name + ", This is an email");
Logger.log("mail sent")
var response = ui.alert("mail was send to "+name, ui.ButtonSet.OK);
UserData[i][2] = true;
}
range.setValues(UserData)
}
Alternative Script
The following script is offered as an alternative. It avoids multiple getRange()/getValue statements and uses a more conventional top-down loop.
function sosendmail01() {
var ui = SpreadsheetApp.getUi();
var ss = SpreadsheetApp.getActiveSpreadsheet();
var s = ss.getSheetByName('Sheet1');
// get the number of rows (Alast)
var Avals = ss.getRange("A2:A").getValues();
var AlastRow = Avals.filter(String).length;
// Logger.log("DEBUG: number of rows = "+AlastRow)
// get the data range
var r = s.getRange(2, 1, AlastRow, 3);// get all the data
// Logger.log("DEBUG: the data range = "+r.getA1Notation())
var v = r.getValues(); // get the data
// loop through the rows of data
for (var i = 0;i<AlastRow;i++){
if (v[i][2] != false) {
// the checkbox is ticked Don't sent an email
// Logger.log("DEBUG: i:"+i+", name = "+v[i][0]+" - the checkbox is ticked");
} else{
// the checkbox IS NOT ticked - send an email
//Logger.log("DEBUG: i:"+i+", name = "+v[i][0]+" checkbox = "+v[i][2]+" - the checkbox is NOT ticked");
var name = v[i][0];
var email = v[i][1];
//MailApp.sendEmail(email, "Test", "Hello " + name + ", This is an email");
Logger.log("DEBUG: mail sent to "+name+" at "+email)
var response = ui.alert("mail was send to "+name, ui.ButtonSet.OK);
v[i][2] = true;
}
}
r.setValues(v);
}

How to traversal a array in JSON Response in Fiddler CustomRules.js?

In CustomRules.js
static function OnBeforeResponse(oSession: Session) {
var responseStringOriginal = oSession.GetResponseBodyAsString();
var responseJSON = Fiddler.WebFormats.JSON.JsonDecode(responseStringOriginal);
var responseJSONObject = responseJSON.JSONObject;
}
There is an array in response responseJSONObject , which are like
[
{
"id": "6661370502453447944"
},
{
"id": "333"
},
...
]
Question 1: How can I get this array's length or traversal this array?
Question 2: How can I save the javascript array to the responseJSON.JSONObject?
I tried
var newJSON = Fiddler.WebFormats.JSON.JsonDecode('{}');
var newJSONObject = newJSON.JSONObject;
newJSONObject['type'] = 'aweme_info'; //ok
newJSONObject['aweme_length'] = 3; //ok
newJSONObject['k']['kell'] = 'good'; //failed
var tpArray = new Array();
for (var i = 1; i < 3; i++) {
tpArray.push(i);
}
var jsonString = JSON.stringify(tpArray); // failed
// how can I convert tpArray to JSON?
Question 3: Where can I find any documentation about this object "Fiddler.WebFormats.JSON", like what method and properties it have.
I tried several ways but nothing works and I can't using the JSON.parse() function in this script.
I also google for the documents of this object (Fiddler.WebFormats.JSON) and found nothing.
Thank you very much and welcome reply any infomation.
https://learn.microsoft.com/en-us/dotnet/api/system.collections.hashtable?view=netframework-4.7.2
This script syntax is very similar to DOTNET. You can read the doc above to find the answers.

xpages typeahead autocomplete

i couldnt do aautocopmlete edit box. i want to take names from another database. i wrote my code to typeahead's value list. but it dont work. i am using same server but different database.anybody help me ? here is my code:
//Getting the view containing a document for each of the employees
var searchView:NotesView = session.getDatabase("servername","test/application name.nsf")
.getView("viewname");
// Creating a Lotus Notes search query. Notice the reference to lupkey!
var query = "(FIELD Ad Soyad CONTAINS *" + lupkey +"*)";
// Creating an array to store hits in
var searchOutput:Array = ["å","åå"];
// Doing the actual search
var hits = searchView.FTSearch(query);
var entries = searchView.getAllEntries();
var entry = entries.getFirstEntry();
//Sort the array manually, since Notes doesn't want to sort them alphabetically
for (i=0; i<hits; i++) {
searchOutput.push(entry.getColumnValues()[0]);
entry = entries.getNextEntry();
}
searchOutput.sort();
// Build the resulting output HTML code
var result = "<ul><li><span class='informal'>Suggestions:</span></li></ul>";
var limit = Math.min(hits,20);
for (j=0; j<limit; j++) {
var name = searchOutput[j].toString();
var start = name.indexOfIgnoreCase(lupkey)
var stop = start + lupkey.length;
//Make the matching part of the name bold
name = name.insert("</b>",stop).insert("<b>",start);
result += "<li>" + name + "</li>";
}
result += "</ul>";
return result;
There are plenty of issues with your code:
the query can't return any result since your field has a space in it
Do you really need an FTSearch to return values and not a sorted view?
the typeahead -as the name suggest- presents values that match left to right and not somewhere substring. If you need that you need to roll your own typeahead function using Ajax
The typeahead function doesn't take a parameter, so your lupkey doesn't go anywhere. The function needs to return all values and XPages will do the matching
Instead of copying one by one into an array for sorting, copy the returning Vector() into a TreeSet(). This is one line, sorts it and removes duplicates
To get it working check this example based on dojo, previously asked here. You will need the REST control
i do it like that
var directoryTypeahead = function (searchValue:string) {
// update the following line to point to your real directory
//var directory:NotesDatabase = session.getDatabase(database.getServer(), "names.nsf");
var directory:NotesDatabase = session.getDatabase(database.getServer(), "org/test.nsf");
var allUsers:NotesView = directory.getView("SVFHP2");
var matches = {};
var includeForm = {
Person: true,
Group: true
}
searchValue = searchValue.replace("I","i")
var matchingEntries:NotesViewEntryCollection = allUsers.getAllEntriesByKey(searchValue, false);
var entry:NotesViewEntry = matchingEntries.getFirstEntry();
var resultCount:int = 0;
while (entry != null) {
var matchDoc:NotesDocument = entry.getDocument();
var matchType:string = matchDoc.getItemValueString("Form");
//if (includeForm[matchType]) { // ignore if not person or group
var fullName:string = matchDoc.getItemValue("Name").elementAt(0) + " " + matchDoc.getItemValue("Title").elementAt(0);
if (!(matches[fullName])) { // skip if already stored
resultCount++;
var matchName:NotesName = session.createName(fullName);
matches[fullName] = {
cn: matchName.getCommon(),
photo: matchDoc.getItemValueString("Photo"),
job: matchDoc.getItemValueString("sum"),
email: matchDoc.getItemValueString("email"),
}
}
// }
/*if (resultCount > 15) {
entry = null; // limit the results to first 10 found
}
else {*/
entry = matchingEntries.getNextEntry(entry);
//}
};
}

How can I save an Email to a Google Sites page using AppsScript

I often have something on my mobile phone that I'd like to keep for future reference. Maybe a photo or an interesting link to an article to read later on a computer.
How can I save this information via email on my phone so that the email content is stored in a Google Sites page using Google AppsScript
This apps script code works. Have it trigger on a timer (say every 5mins) and any emails sent to your gmail account with emailarch in the subject will be added to the page as child pages with attachments. The parent page list will be updated.
The Sites page should be of type List with two text columns Date and Item.
/**
*/
function createEmailArch() {
var site = 'YOURSITE';
var page_name = 'APAGEINYOURSITE';
var site_url = 'https://sites.google.com/site/'+site+'/'+page_name;
var site = SitesApp.getSite(site);
var page = site.getChildByName(page_name);
var curr_date = new Date();
var curr_date_fmt = Utilities.formatDate(curr_date,'Australia/Melbourne','yyyy-MM-dd HH:mm:ss');
var threads = GmailApp.search('subject:"emailarch" is:unread');
for ( var j = 0 ; j<threads.length;j++) {
var messages = threads[j].getMessages();
for ( var i = 0 ; i < messages.length; i++ ) {
var message = messages[i];
var subj = message.getSubject();
var body = message.getBody();
var mdte = message.getDate();
var mfrm = message.getFrom();
var meto = message.getTo();
var atta = message.getAttachments();
var cont = "Subject : "+subj+"<br/>"+
"To : "+meto+"<br/>"+
"From : "+mfrm+"<br/>"+
"Date : "+mdte+"<br/>"+
body;
var dte2 = Utilities.formatDate(curr_date,"Australia/Melbourne","yyyy_MM_dd_HH_mm_ss")+"_"+j+"_"+i;
for ( var k=0;k<atta.length;k++) {
var iname = atta[k].getName();
if ( atta[k].getContentType().indexOf('image')>=0 ) { // If attachment is an image show inline
cont = cont +"<hr/>"+
"<div style='display:block;text-align:left'>"+
"<a href='"+site_url+"/"+dte2+"/"+iname+"?attredirects=0' imageanchor='1'>"+
"<img src='"+site_url+"/"+dte2+"/"+iname+"?height=400&width=224' border='0' height='400' width='224'>"+
"</a></div><br/>";
}
}
var p = page.createWebPage(curr_date_fmt,dte2,cont);
for ( var k=0;k<atta.length;k++) {
p.addHostedAttachment(atta[k]);
}
page.addListItem( [curr_date_fmt, "<a href='"+site_url+"/"+dte2+"'>"+subj+"</a>"]);
message.markRead();
}
}
};