About extracting G-mails to a Google spreadsheet, how can I do to include an IF for dismissing specific e-mails by subject? For example: e-mails responses (with "RE:" in subject). I don't want these e-mails in my spreadsheet.
I've tried with a LOOP but it didn't work because LOOP keeps sending all e-mails to my spreadsheet without a previous selection.
Here's the code:
function GetEmails() {
var label = GmailApp.getUserLabelByName("MY LABEL");
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 message = messages[j];
var from = message.getFrom()
var to = message.getTo();
var subject = message.getSubject();
var RE = subject.startsWith("RE:")
if ([RE != "RE:") {
process1(message);
} else {
process2(message)
}
}
}
function process1(message) {
var body = message.getPlainBody();
var subject = message.getSubject();
var date = message.getDate();
var from = message.getFrom();
var url = "GOOGLE SPREADSHEET"
var ss = SpreadsheetApp.openByUrl(url)
var sheet = ss.getActiveSheet();
sheet.appendRow([date, from, subject, body]);
}
function process2(message) {
var body = message.getPlainBody();
var subject = message.getSubject();
var date = message.getDate();
var from = message.getFrom();
var url = "GOOGLE SPREADSHEET"
var ss = SpreadsheetApp.openByUrl(url)
var sheet = ss.getActiveSheet();
sheet.appendRow([date, from, subject, body]);
}
}
RE is a boolean in your script.
Also DRY (Don't Repeat Yourself)
You likely meant to do
const url = "GOOGLE SPREADSHEET";
const ss = SpreadsheetApp.openByUrl(url);
const sheet = ss.getActiveSheet();
function process(message) {
var subject = message.getSubject();
if (subject.toUpperCase().startsWith("RE:")) {
return; // ignore RE
}
var body = message.getPlainBody();
var date = message.getDate();
var from = message.getFrom();
sheet.appendRow([date, from, subject, body]);
}
function GetEmails() {
var label = GmailApp.getUserLabelByName("MY LABEL");
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++) {
process(messages[j]);
}
}
}
Related
Using app scripts I'm trying to extract all the email addresses from email messages and put them in an array. From my console.log messages, I'm getting stuck because it looks like instead of an array I just get a string. i'm not too familiar with javascript. Any help would be great. I'm looking for an array of email address. The methods of message.get() return a string. I want to split out the email address and create a single, unified array.
var ui = SpreadsheetApp.getUi();
function onOpen(e){
ui.createMenu("Gmail Manager").addItem("Get Emails by Label", "getGmailEmails").addToUi();
}
function getGmailEmails(){
var label = GmailApp.getUserLabelByName("MyLabel");
var threads = label.getThreads();
var fullArray = [];
for(var i = threads.length - 1; i >=0; i--){
var messages = threads[i].getMessages();
for (var j = 0; j <messages.length; j++){
var message = messages[j];
if (message.isUnread()){
fullArray.push(extractDetails(message));
}
}
}
console.log("FullArray:"+fullArray);
for(var i=0; i<fullArray.length; i++){
console.log("printing array " + i + ": "+fullArray[i])
}
}
function extractDetails(message){
var dateTime = message.getDate();
var subjectText = message.getSubject();
var senderDetails = message.getFrom();
var ccEmails = message.getCc();
var replyEmail = message.getReplyTo();
var toEmail = message.getTo();
var emailArray = []
var senderArray = senderDetails.split(',');
var ccArray = ccEmails.split(',');
var replyArray = replyEmail.split(',');
var toArray = toEmail.split(',');
for (var i =0 ; i<toArray.length; i++){
console.log("toArray Loop"+ i + " : "+ toArray[i]);
emailArray.push([toArray[i]]);
}
for (var i =0 ; i<ccArray.length; i++){
console.log("ccArray Loop"+ i + " : "+ ccArray[i]);
emailArray.push([ccArray[i]]);
}
console.log("Email Array: "+ emailArray);
var activeSheet = SpreadsheetApp.getActiveSpreadsheet().getActiveSheet();
activeSheet.appendRow([dateTime, senderDetails, subjectText, ccEmails,replyEmail,toEmail,emailArray]);
return emailArray;
}
I think the problem is just the console output. If you change console.log("Email Array: "+ emailArray); to console.log("Email Array: ", emailArray);, then it shows an array of arrays. You could simplify your extract method as follows:
function extractDetails(message) {
/* ... */
var senderDetails = message.getFrom();
var ccEmails = message.getCc();
var replyEmails = message.getReplyTo();
var toEmails = message.getTo();
let emailArray = [senderDetails, ccEmails, replyEmails, toEmails].reduce(
(array, string) => {
//remove names (like "Name <name#company.com>") and filter empty values
let emails = string
.split(/\s*,\s*/)
.map(e => e.replace(/.*?([^#<\s]+#[^#\s>]+).*?/g, "$1"))
.filter(Boolean);
if(emails.length > 0)
return array.concat(emails)
return array
}, []);
/* ... */
}
I want to bigquery table data using app script ,I am using this code but i am getting job id, i dont job id i want table data please help me this.
function runQuery() {
DriveApp.getRootFolder();
var projectId = 'imran-338706';
var request = {
query: 'SELECT network_affiliate_name FROM `imran-338706.imranabc.bhk` LIMIT 10',
useLegacySql: false
}
var queryResults = BigQuery.Jobs.query(request, projectId);
var jobId = queryResults.jobReference.jobId;
console.log(queryResults)
}
I verified using the following code for queries returning small amount of data :
function runQuery() {
DriveApp.getRootFolder();
var projectId = ProjectID;
var request = {
query: 'SELECT * from `bigquery-public-data.austin_311.311_service_requests` limit 2',
useLegacySql: false
}
var queryResults = BigQuery.Jobs.query(request, projectId);
var jobId = queryResults.jobReference.jobId;
var rows = queryResults.rows;
var header = "";
for (var i = 0; i < queryResults.schema.fields.length; i++){
header+= " " + queryResults.schema.fields[i].name;
}
console.log(header)
var data = new Array(rows.length);
var string = ""
for (var i = 0; i < rows.length; i++) {
var cols = rows[i].f;
data[i] = new Array(cols.length);
for (var j = 0; j < cols.length; j++) {
data[i][j]= cols[j].v;
string+= " "+ data[i][j]
}
console.log(string);
}
}
It gave the schema and row contents:
I am trying to make a script to automate deleting duplicate data based on column A. This is the current script I am using and it works.
// This scripts works but deleting new data instead of old data
function removeDuplicates() {
var sheetName = SpreadsheetApp.getActiveSpreadsheet().getActiveSheet().getName();
var ss = SpreadsheetApp.getActive();
var sh = ss.getSheetByName(sheetName);
var vA = sh.getDataRange().getValues();
var hA = vA[0];
var hObj = {};
hA.forEach(function(e, i) {
hObj[e] = i;
});
var uA = [];
var d = 0;
for (var i = 0; i <= vA.length; i++) {
if (uA.indexOf(vA[i][hObj['key']]) == -1) {
uA.push(vA[i][hObj['key']]);
} else {
//sh.deleteRow(i + 1 - d++);
sh.deleteRow((parseInt(i)+1) - d);
d++;
}
}
};
But this one is deleting the newly added row, what I want to achieve is it should delete the old duplicate row instead. How can I do that?
In else part instead of using i which represent your current row, use the indexOf the row you want to delete. Delete it first and then push the new one into array
// This scripts works but deleting new data instead of old data
function removeDuplicates() {
var sheetName = SpreadsheetApp.getActiveSpreadsheet().getActiveSheet().getName();
var ss = SpreadsheetApp.getActive();
var sh = ss.getSheetByName(sheetName);
var vA = sh.getDataRange().getValues();
var hA = vA[0];
var hObj = {};
hA.forEach(function(e, i) {
hObj[e] = i;
});
var uA = [];
var d = 0;
for (var i = 0; i <= vA.length; i++) {
if (uA.indexOf(vA[i][hObj['key']]) == -1) {
uA.push(vA[i][hObj['key']]);
} else {
//sh.deleteRow(i + 1 - d++);
let j = uA.indexOf(vA[i][hObj['key']]);
sh.deleteRow((parseInt(j)+1) - d);
d++;
uA.push(vA[i][hObj['key']]);
}
}
};
I am using this function to pull information from coinmarketcap using their v2 api. The problem I am getting is that if a "website_slug" does not exist on coinmarketcap, I get an incorrect range width error instead of the function just putting xxx in the cell. This can be recreated by having a cell in column B that doesn't match a website_slug on cmc (https://api.coinmarketcap.com/v2/ticker/).
function getMarketCap(sheetname) {
var ss = SpreadsheetApp.getActiveSpreadsheet();
var sheet = ss.getSheetByName(sheetname);
var assets = [];
var idRange = sheet.getRange("B1:B");
var lastRow = getLastRowOfRange(idRange);
var cellRange = sheet.getRange(1, 2, lastRow).getValues();
var mcRange = sheet.getRange(1, 3, lastRow);
var mcValues = [];
for (var i = 0; i < cellRange.length; i++) {
assets[i] = cellRange[i];
}
var req = [];
for (var i = 0; i < 16; i++) {
req.push({
muteHttpExceptions: true,
method: "get",
url: "https://api.coinmarketcap.com/v2/ticker/?start=" + (i * 100 + 1),
});
}
var responses = UrlFetchApp.fetchAll(req);
var res = responses.filter(function(e){return e.getResponseCode() == 200}).map(function(e){return JSON.parse(e.getContentText())});
if (responses.length != res.length) Logger.log("%s errors occurred.", responses.length - res.length);
var mcValues = [];
assets.forEach(function(e, h) {
mcValues[h] = []
res.some(function(f) {
Object.keys(f.data).some(function(g) {
if (f.data[g].website_slug == e[0]) {
mcValues[h][0] = f.data[g].quotes.USD.market_cap;
return true;
}
});
if (mcValues[h][0]) return true;
});
if (!mcValues[h][0]) mcValues[h][0] = 'xxx';
});
mcRange.setValues(mcValues);
}
I am using this code but I can't see anything in the logger. I can just see a message "Preparing for execution"
function testfunc() {
var s = SpreadsheetApp.getActiveSpreadsheet()
var sheet = s.getSheetByName("data")
var lastRow = sheet.getLastRow() - 1
var data = sheet.getRange(2,2,lastRow,5).getValues()
var fms = s.getSheetByName("FMS")
for (var i = 0;i < data.length; ++i){
var row = data[i]
var a = row[0]
var b = row[1]
var c = row[2]
var d = row[3]
var e = row[4]
Logger.log(i)
if (i = 1) {
Logger.log(i)
}
}
}
Where did I go wrong?
EDIT: As pointed out by #FedericoklezCulloca, I was missing an equal to sign in my if statement. The code should be :
function testfunc() {
var s = SpreadsheetApp.getActiveSpreadsheet()
var sheet = s.getSheetByName("data")
var lastRow = sheet.getLastRow() - 1
var data = sheet.getRange(2,2,lastRow,5).getValues()
var fms = s.getSheetByName("FMS")
for (var i = 0;i < data.length; ++i){
var row = data[i]
var a = row[0]
var b = row[1]
var c = row[2]
var d = row[3]
var e = row[4]
Logger.log(i)
if (i == 1) {
Logger.log(i)
}
}
}