If new contact get address, subject, message - javascript

I need a program for google script that tells me if I have an email address in my contacts or not.
I get many emails from vendors each day and many of them are completely new contacts. I need a program that makes a list of only the new contacts so I can decide which contact group to add them too.
Basic structure of what I'm looking for:
Will run this program every 5 minutes (I can set that up.)
-Checks emails with yellow or blue star for email address of recipient and sender. filters out my email address.
-Checks the email address against all my contacts. If the email address does not appear in my google contacts I need:
Email address, subject line, message text, additional thread message, additional thread message... in seperate columns in a spreadsheet.
I will then go through this information manually to decide which groups to put them in.
Thank you for your help!!!
UPDATE//////////////////////////////update.3
Here's where I'm at. This is working on and off. One time I run it it works, another time it doesn't. REally annoying. If anyone can see any glairing problems let me know. Especially hard to get the if sndr and if rcpnt to return false to run the rest of the program. I've tried about 20 ways!!!
//http://webapps.stackexchange.com/questions/9813/get-e-mail-addresses-from-gmail-messages-received
/////////////NESTED LOOP METHOD
function newEmailAddressList(){
var ss = SpreadsheetApp.getActiveSpreadsheet();
var sheet = ss.getSheetByName("NewEmails");
var range = sheet.getRange("A2:BA");
var addrA;
range.clearContent(); //May need to change this to my delete function to speed things up.
var contact = ContactsApp.getContacts();
for(var i = 0;i < contact.length;i++){
var addrA = [];
var start;
var addresses = contact[i].getEmails();
for(var j = 0;j < addresses.length;j++){
addrA.push(addresses[j].getAddress());
};
};
sheet.getRange('H1').setValue("List Created");
for (var i=0; i<50; i++){
var threads = GmailApp.getInboxThreads(0,50)[i];
var messages = threads.getMessages()[0];
var sndr = messages.getFrom().replace(/^.+<([^>]+)>$/, "$1"); //http://stackoverflow.com/questions/26242591/is-there-a-way-to-get-the-specific-email-address-from-a-gmail-message-object-in
var rcpnt = messages.getTo().replace(/^.+<([^>]+)>$/, "$1");
function contains(addrA, sndr) {
for (var i = 0; i < addrA.length; i++) {
if (addrA[i] === sndr) {
sheet.appendRow("Emails Match");
}else{
var dat = messages.getDate();
//var sndr = messages.getFrom();
//var rcpnt = messages.getTo();
var sub = messages.getSubject();
var msg = messages.getPlainBody();
var info = [dat,sndr,rcpnt,sub,msg];
sheet.appendRow(info); //appendRow only works with sheet class not range class
};
};
};
};
};

Well, I'll give you a start. And keep in my that I've never really worked with GmailApp in the past so all of this information is pretty much readily available to any who opens the code editor clicks on help and then clicks on API Reference. Everything you need to know about Google Scripts is right there organized about as well as it's ever been. They have really improved their documentation since the first time I've looked at it several years ago.
So I'm giving you some functions that will get all of your contact emails, your from emails from your inbox and and your emails.
function myContacts()
{
var s = '';
var br = '<br />';
var contact = ContactsApp.getContacts();
for(var i = 0;i < contact.length;i++)
{
var addrA = [];
var addresses = contact[i].getEmails();
for(var j = 0;j < addresses.length;j++)
{
s += addresses[j].getAddress() + br;
addrA.push(addresses[j].getAddress());
}
}
dispStatus('Contact Emails',s, 800, 400);
}
function MyFroms()
{
var threads = GmailApp.getInboxThreads();
var s = '';
for(var i = 0; i < threads.length; i++)
{
var msg = threads[i].getMessages();
for(var j = 0; j < msg.length;j++)
{
s += msg[j].getFrom() + '<br />';
}
}
dispStatus('My Messages', s , 800 , 400);
}
function MyMessages()
{
var threads = GmailApp.getInboxThreads();
var s = '';
for(var i = 0; i < threads.length; i++)
{
var msg = threads[i].getMessages();
for(var j = 0; j < msg.length;j++)
{
s += 'Message' + j+1 + '<br />';
s += msg[j].getFrom() + '<br />';
s += msg[j].getBody() + '<br />';
}
}
dispStatus('My Messages', s , 800 , 400);
}
function dispStatus(title,html,width,height)
{
var title = typeof(title) !== 'undefined' ? title : 'No Title Provided';
var width = typeof(width) !== 'undefined' ? width : 800;
var height = typeof(height) !== 'undefined' ? height : 400;
var html = typeof(html) !== 'undefined' ? html : '<p>No html provided.</p>';
var htmlOutput = HtmlService
.createHtmlOutput(html)
.setWidth(width)
.setHeight(height);
SpreadsheetApp.getUi().showModelessDialog(htmlOutput, title);
}
It's not a complete answer. But hopefully it will encourage you to jump in get your feet wet and exercise your mental muscles and bring us back at least a partially working skeleton of a program that we can help you get running.

Related

google scripts throwing not a function error for getMessages()

I am trying to create a script for an autoreply function. I am currently trying to grab each of the emails assigned to a specific label and grab specific details off of each email, however I am receiving an error stating TypeError: threads.getMessages is not a function, even though I have triple checked that this is, indeed, a function of the GMAIL scripting. Have I done something wrong here in this code that may be causing this error?
var labelName = "auto-reply-incoming";
var receivedCount = 0;
// extract emails from label in Gmail
function extractEmails() {
// get all email threads that match label
var receivedSearchQuery = "label:"+labelName+" -is:sent";
var threads = GmailApp.search(receivedSearchQuery, 0, 500);
for (var i=0; i<threads.length; i++) {
//count received emails in label
receivedCount = receivedCount + threads[i].getMessageCount();
//get body of each email
var message = threads.getMessages()[i].getBody();
//get recipient of each email
var recipient = threads.getMessages()[i].getTo();
}
Logger.log(receivedCount);
Logger.log(recipient);
}
The problem occurs because the code is using the threads iterator that might be bigger than the number of messages on certain threads, more specifically, the problem is in the following lines:
//get body of each email
var message = threads.getMessages()[i].getBody();
//get recipient of each email
var recipient = threads.getMessages()[i].getTo();
Here is a quick fix (replace the above, by the following)
var messages = threads[i].getMessages();
for( j = 0; j < messages.length; j++){
//get body of each email
var message = messages[j].getBody();
//get recipient of each email
var recipient = messages[j].getTo();
}
Note: Logger.log(recipient) will log the recipient of the last message of the last thread.
Try this:
function extractEmails() {
var labelName = "auto-reply-incoming";
var receivedCount = 0;
var receivedSearchQuery = "label:" + labelName + " -is:sent";
var ts = GmailApp.search(receivedSearchQuery, 0, 500);
var a = [];
ts.forEach((t, i) => {
let ms = t.getMessages();
ms.forEach((m, j) => {
let msg = m.getBody();
let rec = m.getTo();
a.push({ threadindex: j, messageindex: i, message: msg, recipient: rec })
});
});
Logger.log(JSON.stringify(a));
}

How do i retrieve their timestamp from an email

Writing a small script that pulls messages with a label and outputs the subject to a Slack channel.
I've gotten it down ( customized to from someone ) but need further help on where to get the time from.
/* Credit: gist.github.com/andrewmwilson */
function sendEmailsToSlack() {
var label = GmailApp.getUserLabelByName('!urgent');
var messages = [];
var threads = label.getThreads();
for (var i = 0; i < threads.length; i++) {
messages = messages.concat(threads[i].getMessages())
}
for (var i = 0; i < messages.length; i++) {
var message = messages[i];
Logger.log(message);
var output = '*State Change Detected*';
output += '\n*subject:* ' + message.getSubject();
Logger.log(output);
You can use the getDate() method on a message:
var message = messages[0]; // Get first message
Logger.log(message.getDate()); // Log date and time of the message

Google Form Script Population

I am trying to populate a google form with questions scraped from a google sheet. Currently when I run my code I am getting the questions created, but only 25% or so actually have the string, the rest are simply blank. The questions that appear correctly change every time I run the script. It is seemingly random.
function formPopulation() {
var ss = SpreadsheetApp.openById("--");
var sheet = ss.getSheetByName('Tracker');
var auditTool = ss.getSheetByName('Audit Tool');
var validatorInfo = ss.getSheetByName('Validator Info');
//Sheet Info
var rows = auditTool.getLastRow(); //Number of Rows
var columns = auditTool.getLastColumn(); //Number of Columns
var startRow = 1;
var startColumn = 1;
var dataRange = auditTool.getRange(startRow, startColumn, rows, columns);
//getRange(first row of data, first column of data, last row of data, last column of data)
var data = dataRange.getValues();
//Sets working range of script
var form = FormApp.openById("--");
var item = form.addListItem();
var entityName = "";
var arrayOfEntities = [];
var newEntity = '';
for (var i = 4; i < columns; i++) {
//4 because that is where entity names begin
entityName = data[i][2];
Logger.log('entityName: ' + entityName);
newItem = item.createChoice(entityName);
arrayOfEntities.push(newItem);
};
item.setTitle("Select Entity").setChoices(arrayOfEntities);
var requirement = "";
var arrayOfRequirements = [];
var newRequirement = '';
for (var j = 5; j < rows; j++) {
//5 because that is where Requirements begin
if (data[0][j] != null) {
requirement = data[0][j];
if (requirement != "" || requirment != null){
requirement = "question #" + j;
Logger.log('requirement: ' + requirement);
form.addMultipleChoiceItem().setTitle(requirement).setChoiceValues(['Complete', 'Incomplete']);
};
};
};
};
The first question is supposed to be a multiple choice item where each 'entity' is an option. The remainder of the questions are supposed to be whether each 'requirement' is marked complete or incomplete.
Here is the spreadsheet I am working from
you have a typo:
if (requirement != "" || requirment != null){
should be 'requirement'
Here in last forloop
requirement = "question #" + j;
Please verify, is it ok ? or you should use
requirement = "question #" + j + ' ' +data[0][j];

Ignoring ' from javascript code, SQLite

I have a french category named piqûres d'insectes that I am pulling from a SQLite database. Unfortunately, the ' in the category keeps breaking my javascript code, as seen in my pictures where it turns my breadcrumbs into undefined (half the word is missing as well clearly from the apostrophe). Is there a way I can pull this as just text so it does not break my code?
Javascript:
function txSuccessListAddSymptoms(tx,results) {
//console.log("Read Additional Symptoms success");
var category = getUrlVars().category;
var mainsymptom = getUrlVars().mainsymptom;
var len = results.rows.length;
var addSymp;
for (var i=0; i < len; i = i + 1) {
addSymp = results.rows.item(i);
};
$('#addSymps').listview('refresh');
}
You can use an escape character: \'
So for example try to use: piqûres d\'insectes
You can use the original name by adding this lines of code:
var str = getUrlVars().category;
var category = str.replace("'", "\'");
This code changes the ' to \' if it is in the name.
I hope this helped for you
EDIT::
Soo.. this would be your script:
function txSuccessListAddSymptoms(tx,results) {
//console.log("Read Additional Symptoms success");
var str = getUrlVars().category;
var category = str.replace("'", "\'");
var mainsymptom = getUrlVars().mainsymptom;
var len = results.rows.length;
var addSymp;
for (var i=0; i < len; i = i + 1) {
addSymp = results.rows.item(i);
};
$('#addSymps').listview('refresh');
}

ActiveXObject Number of rows counter

I have this piece of code:
function GetData(evt){
var adresses = new Array();
var j = 0;
var excel = new ActiveXObject("Excel.Application");
var fil = document.getElementById("file");
var excel_file = excel.Workbooks.Open(fil.value);
var excel_sheet = excel.Worksheets(1);
for(var i=2;i<500;i++){
var morada = excel_sheet.Range("E"+ i );
var localidade = excel_sheet.Range("C"+ i );
var pais = excel_sheet.Range("A"+i);
adresses[j] = (morada + ", " + localidade + ", " + pais);
j++;
}
for(var k = 0; k<j; k++) {
codeAddress(adresses[k]);
}
}
It receives an excel file and processes the data like I want. The thing is, it is very hard coded.
For instant, in this for:
for(var i=2;i<500;i++)
I am using 500, but I would like to use the number of rows in the sheet. I have already tried a few things like rows.count and whatever and I gave some alerts to see the results, but I just can't find the one who tells me the number of rows.
Anyone know how to do it?
Try that :
excel_sheet.UsedRange.Rows.Count
Does it works ?

Categories

Resources