How can I get the all messages in the inbox? (include reply) - javascript

i use the following code in Google Apps Script and i wanna get all messages in the inbox. This code gives "Cannot convert Array to number[][]. (line 19, file "Code")" error. How can i fix this code?
var myspreadsheet = SpreadsheetApp.getActiveSpreadsheet();
var mysheet = myspreadsheet.getSheets()[0];
var start = 0;
var max = 19;
var count = 0;
while (count < 7) {
var threads = GmailApp.getInboxThreads(start, max);
var messages = GmailApp.getMessagesForThreads(threads);
//var froms = [];
messages.get
for (var i = 0; i < threads.length; i++) {
var thisThread = threads[i];
var messages = thisThread.getMessages();
var messageCount = thisThread.getMessageCount();
for ( var m = 0; m<=messageCount; m++) {
var lastMessage = messages[m];
froms = ([lastMessage.getId(), lastMessage.getSubject(), lastMessage.getTo(), lastMessage.getFrom(), lastMessage.getCc(), JSON.stringify(lastMessage.getDate()), lastMessage.getReplyTo()]);
mysheet.getRange(1, 1, froms.length, 7).setValues(froms);
froms = [];
}
}
start = start + 100;
count++;
}
}

Try changing this: froms = ([lastMessage.getId(), lastMessage.getSubject(), lastMessage.getTo(), lastMessage.getFrom(), lastMessage.getCc(), JSON.stringify(lastMessage.getDate()), lastMessage.getReplyTo()]);
to this: froms = ([[lastMessage.getId(), lastMessage.getSubject(), lastMessage.getTo(), lastMessage.getFrom(), lastMessage.getCc(), JSON.stringify(lastMessage.getDate()), lastMessage.getReplyTo()]]);
But really I think you have even bigger problems with your script.
I'd use something like this. But I can't test it very well because I don't keep a lot of junk in my inbox.
function emailsStuff() {
var ss=SpreadsheetApp.getActive();
var sh=ss.getSheets()[0];
sh.clearContents();
var threads=GmailApp.getInboxThreads()
for(var i=0;i<threads.length;i++) {
var messages=GmailApp.getMessagesForThread(threads[i]);
for(var j=0;j<messages.length;j++) {
var msg=messages[j];
sh.appendRow([msg.getId(), msg.getSubject(), msg.getTo(), msg.getFrom(), msg.getCc(), JSON.stringify(msg.getDate()), msg.getReplyTo()]);
}
}
}

Related

Removing decimal from string

I'm trying to understand how I can remove a decimal. I have tried Math.trunc() but it never seems to remove. Logger.log(esValues.length) prints 500.0, I tried adding var removeDecimal = Math.trunc(esValues.length) then printing removeDecimal but I still get 500.0
var ss = SpreadsheetApp.getActiveSpreadsheet();
var es = ss.getSheetByName("School1");
var ms = ss.getSheetByName("School2");
var hs = ss.getSheetByName("School3");
var esValues = es.getDataRange().getValues();
var counterDell = 0;
var counterHP = 0;
//var esValues = es.getRange('A:C').getValues();
Logger.log(esValues.length); //This prints 500.0, Also tried adding here Logger.log(Math.trunc(esValues.length))
for (var i = 0; i < esValues.length; i++) {
var data = esValues[i];
var first = data[1];
var last = data[0];
var middle = data[2];
var studentid = data[3];
var device = data[4];
if (device.includes("Dell")) {
counterDell++;
} else if (device.includes("HP")) {
counterHP++;
}
}
Logger.log(`Dell count is ${counterDell}`)
Logger.log(`Hp count is ${counterHP}`)
}
Logger.log(esValues.length.split('.')[0])
breaks the decimal into integer and decimal portions, then we discard the decimal portion.
Actually just not using the logger will elimate the .0. For some stupid reason it has always done that.
function lfunko() {
var ss = SpreadsheetApp.getActive();
var es = ss.getSheetByName("School1");
var vs = es.getDataRange().getValues();
var counterDell = 0;
var counterHP =
for (var i = 0; i < vs.length; i++) {
var device = vs[4];
if (device.includes("Dell")) {
counterDell++;
} else if (device.includes("HP")) {
counterHP++;
}
}
const msg = `HP: ${counterHP} DELL: ${counterDell}`
SpreadsheetApp.getUi().showModelessDialog(HtmlService.createHtmlOutput(msg),"Counts");
}

How to prevent duplicate emails being added to google sheet - App Script

I am new to App Script. My code is below. I have been trying to take data out of an email and put it into different columns in google sheets. I have managed to achieve this and it works but because labels are applied to threads I get duplicates!
I have tried to figure out how to stop this from happening by using the email ID, date etc but I haven't been successful. Any help would be greatly appreciated.
function email_sheet() {
var ss = SpreadsheetApp.openById("");
var sheet = ss.getSheetByName("Sheet1");
var label = GmailApp.getUserLabelByName("ChosenLabel");
var threads = label.getThreads();
for (var i = 0; i < threads.length; i++) {
var messages = threads[i].getMessages();
for (var j = 0; j < messages.length; j++) {
var date = messages[j].getDate();
var body = messages[j].getPlainBody();
var name = "";
var accnum = "";
var paytype ="";
var amount = "";
var status = "";
/** Break Down the Email */
if(body.indexOf("Recipient : ")>0) {
var end = body.substring(body.indexOf("Recipient : ")+12,body.length);
name = end.substring(0, end.indexOf("\n"));
}
if(body.indexOf("AN")>0) {
var end = body.substring(body.indexOf("AN")+2,body.length);
account = end.substring(0, end.indexOf("\n"));
var [accnum, paytype] = account.split(" ");
}
if(body.indexOf("Amount : ")>0) {
var end = body.substring(body.indexOf("Amount : ")+9,body.length);
amount = end.substring(0, end.indexOf("\n"));
}
if(body.indexOf("Transaction Status : ")>0) {
var end = body.substring(body.indexOf("Transaction Status : ")+21,body.length);
status = end.substring(0, end.indexOf("\n"));
}
sheet.appendRow([date, name, accnum, paytype, amount, status]);
}
threads[i].removeLabel(label);
threads[i].addLabel(GmailApp.getUserLabelByName("All Transactions"))
}
} ```
You can for instance limit to unread mails and at the end mark them as already read, for instance
function mail() {
var requete ="is:unread {label:ChosenLabel label:OtherLabel}"
var ss = SpreadsheetApp.getActive().getSheetByName("Mail");
var threads = GmailApp.search(requete);
for (var i = 0; i < threads.length; i++) {
var messages = threads[i].getMessages();
for (var j = 0; j < messages.length; j++) {
var msg = messages[j].getPlainBody();
var sub = messages[j].getSubject();
var dat = messages[j].getDate();
ss.appendRow([dat, sub, msg])
}
}
GmailApp.markThreadsRead(threads);
}

How to set data from an array to another array to improve performance

I'm currently developing a sheet that shows results from a set of data based on some filters but the data loads to slowly when getting the results, I've tried to follow the Best Practices from Google Documentacion with no luck, how can I set an array for the data to load faster?
Below is the code commented with what I've already tried
function realizarBusqueda() {
var inicio = SpreadsheetApp.getActive().getSheetByName("INICIO");
var aux_tags = SpreadsheetApp.getActive().getSheetByName("Aux_Tags");
var data = SpreadsheetApp.getActive().getSheetByName("Data");
var data_lc = data.getLastColumn();
var data_lr = data.getLastRow();
var searchRange = data.getRange(2,1, data_lr, data_lc);
var inicio_lc = inicio.getLastColumn();
inicio.getRange("A8:L1000").clearContent();
inicio.getRange("A8:L1000").clearFormat();
var countRows = inicio.getMaxRows();
inicio.deleteRows(20, (20-countRows)*-1);
if (inicio.getRange("B4").isBlank()) {
inicio.getRange("A8:L1000").clearContent();
inicio.getRange("A8:L1000").clearFormat();
var countRows = inicio.getMaxRows();
inicio.deleteRows(20, (20-countRows)*-1);
SpreadsheetApp.flush();
}
else if ((inicio.getRange("B4").getValue() != "" &&
inicio.getRange("C4").getValue() === "")) {
//filtrado 1
var arrayDatos = searchRange.getValues();
var inicio_fr = 8;
//var row = new Array(11);
for (var j = 2; j <= data_lr; j++) {
//row[j] = new Array(data_lr);
if (aux_tags.getRange("P2").getValue() === arrayDatos[j-2][4]) {
var inicio_fc = 1;
for (var i = 0; i < arrayDatos[j-2].length; i++) {
//row[j][i] = arrayDatos[j-2][i];
var row = arrayDatos[j-2][i];
inicio.getRange(inicio_fr, inicio_fc).setValue(row);
inicio_fc++;
}
inicio_fr++;
}
//inicio.getRange("A8").setValues(row);
}
}
I expect the output to load lots faster, currently what I've tried is commented, the code as-is is working but too slow
I just wanted to update this subject because I figured out myself, see attached the new code with the use of new 2D arrays
...
//filtrado 1
var arrayDatos = searchRange.getValues();
var inicio_fr = 8;
var rows = [];
var row = [];
for (var j = 2; j <= data_lr; j++) {
if (aux_tags.getRange("P2").getValue() === arrayDatos[j-2][4]) {
var inicio_fc = 1;
for (var i = 0; i < arrayDatos[j-2].length; i++) {
row.push(arrayDatos[j-2][i]);
if (i == 11) {
rows.push(row);
row = [];
}
}
}
}
inicio.getRange(8, 1, rows.length, rows[0].length).setValues(rows);
}
Now instead of writing on row at a time, I just write the whole array at once

comparate a elementes inside of an array for get a specific value appscript

I want to do a comparate a elementes inside of an array for get a specific value, how i could do it with this?
var data = sheet.getDataRange().getValues();
var dataToImport = {};
for(var i = 1; i < data.length; i++) {
dataToImport = {
Nivel:data[i][0],
Consumo:data[i][1],
Flujo:data[i][2],
if(dataToImport[Nivel]>99)
{
}
I'm not sure what your looking for but hopefully this will help.
function myfunction()
{
var ss=SpreadsheetApp.getActive();
var sh=ss.getActiveSheet();
var data=sh.getDataRange().getValues();
var dataToImport = {};
for(var i=1;i<data.length;i++)
{
dataToImport = {'Nivel':data[i][0],'Consumo':data[i][1],'Flujo':data[i][2]}
if(dataToImport['Nivel']>99)
{
Logger.log('Nivel greater than 99 dataToImport = %s', dataToImport);
}
Logger.log(dataToImport);
}
}

Google script - parse HTML from Website Forum - and Write Data to Sheet

I'm getting HTML from a forum url, and parsing the post count of the user from their profile page. I don't know how to write the parsed number into the Google spreadsheet.
It should go account by account in column B till last row and update the column A with count.
The script doesn't give me any errors, but it doesn't set the retrieved value into the spreadsheet.
function msg(message){
Browser.msgBox(message);
}
function onOpen() {
var ui = SpreadsheetApp.getUi();
ui.createMenu("Update")
.addItem('Update Table', 'updatePosts')
.addToUi();
}
function getPostCount(profileUrl){
var html = UrlFetchApp.fetch(profileUrl).getContentText();
var sliced = html.slice(0,html.search('Posts Per Day'));
sliced = sliced.slice(sliced.search('<dt>Total Posts</dt>'),sliced.length);
postCount = sliced.slice(sliced.search("<dd> ")+"<dd> ".length,sliced.search("</dd>"));
return postCount;
}
function updatePosts(){
if(arguments[0]===false){
showAlert = false;
} else {
showAlert=true;
}
var spreadSheet = SpreadsheetApp.getActiveSpreadsheet();
var accountSheet = spreadSheet.getSheetByName("account-stats");
var statsLastCol = statsSheet.getLastColumn();
var accountCount = accountSheet.getLastRow();
var newValue = 0;
var oldValue = 0;
var totalNewPosts = 0;
for (var i=2; i<=accountCount; i++){
newValue = parseInt(getPostCount(accountSheet.getRange(i, 9).getValue()));
oldValue = parseInt(accountSheet.getRange(i, 7).getValue());
totalNewPosts = totalNewPosts + newValue - oldValue;
accountSheet.getRange(i, 7).setValue(newValue);
statsSheet.getRange(i,statsLastCol).setValue(newValue-todaysValue);
}
if(showAlert==false){
return 0;
}
msg(totalNewPosts+" new post found!");
}
function valinar(needle, haystack){
haystack = haystack[0];
for (var i in haystack){
if(haystack[i]==needle){
return true;
}
}
return false;
}
The is the first time I'm doing something like this and working from an example from other site.
I have one more question. In function getPostCount I send the function profileurl. Where do I declare that ?
Here is how you get the URL out of the spreadsheet:
function getPostCount(profileUrl){
var ss = SpreadsheetApp.getActiveSpreadsheet();
var thisSheet = ss.getSheetByName("List1");
var getNumberOfRows = thisSheet.getLastRow();
var urlProfile = "";
var sliced = "";
var A_Column = "";
var arrayIndex = 0;
var rngA2Bx = thisSheet.getRange(2, 2, getNumberOfRows, 1).getValues();
for (var i = 2; i < getNumberOfRows + 1; i++) { //Start getting urls from row 2
//Logger.log('count i: ' + i);
arrayIndex = i-2;
urlProfile = rngA2Bx[arrayIndex][0];
//Logger.log('urlProfile: ' + urlProfile);
var html = UrlFetchApp.fetch(urlProfile).getContentText();
sliced = html.slice(0,html.search('Posts Per Day'));
var postCount = sliced.slice(sliced.search("<dd> ")+"<dd> ".length,sliced.search("</dd>"));
sliced = sliced.slice(sliced.search('<dt>Total Posts</dt>'),sliced.length);
postCount = sliced.slice(sliced.search("<dd> ")+"<dd> ".length,sliced.search("</dd>"));
Logger.log('postCount: ' + postCount);
A_Column = thisSheet.getRange(i, 1);
A_Column.setValue(postCount);
};
}
You're missing var in front of one of your variables:
postCount = sliced.slice(sliced.search("<dd> ")+"<dd> ".length,sliced.search("</dd>"));
That won't work. Need to put var in front. var postCount = ....
In this function:
function updatePosts(){
if(arguments[0]===false){
showAlert = false;
} else {
showAlert=true;
}
There is no array named arguments anywhere in your code. Where is arguments defined and how is it getting any values put into it?

Categories