Data conditioning of google gmails/email addresses - javascript

I am trying to make filters for gmail and I need to get the sent TO emails.
The problem is that the emails in the To line of the email can have many different formats. I wanted to see if there was an easier way than what I was doing to unify the formats of the emails. I was just going to account for every case I could find and deal with like that.
function getTo(email) {
// Logs the To lines of up to the first 1-500 emails in your Inbox
var threads = GmailApp.getInboxThreads(0, 75);
for (var i = 0; i < threads.length; i++) {
var messages = threads[i].getMessages();
for (var j = 0; j < messages.length; j++) {
var emailto = messages[j].getTo();
//runs the .to emails through the data conditioning function
//emailprocess(email,emailto)
}
Logger.log(emailto);
}
}
function main () {
var email = Session.getActiveUser().getEmail();
Logger.log(email);
getTo(email)
// createToFilte(toAddress, labelName)
}
function emailprocess(email,emailto){
var emailto = emailto.toLowerCase();
switch (emailto) {
case email:
label = 0;
break;
case "john doe <johndoe#gmail.com>":
label = 0;
break;
case "<johndoe#gmail.com>":
label = 0 ;
break;
default:
label = emailto.replace('johndoe+', '');
label = label.replace("#gmail.com","")
break;
}
}
The emails can be in many different formats here are some:
john doe < johndoe#gmail.com >
johndoe#gmail.com
< johndoe#gmail.com >
johndoe#gmail.com , janedoe#gmail.com
johndoe+65#gmail.com
and maybe only a little more.
Any help would be great. I am also not the best programmer so any way to make this more streamlined would be great.
Solution:
function getTo(email) {
var emailregex = /([a-zA-Z0-9_\.\+-]+#[a-zA-Z0-9-]+\.[a-zA-Z0-9-\.]+)/gm
var threads = GmailApp.getInboxThreads(0, 500); // Logs the To lines of up to the first 1-500 emails in your Inbox
for (var i = 0; i < threads.length; i++) {
var messages = threads[i].getMessages();
for (var j = 0; j < messages.length; j++) {
var emailto = messages[j].getTo()
var emailto = emailto.toLowerCase();
//Logger.log(emailto);
emailto = emailto.match(emailregex); //runs the .to emails through the data conditioning
Logger.log(emailto);
if(emailto != null){
for (var k = 0; k < emailto.length; k++) {
if (emailto[k].indexOf("+") > -1) {
var labelto = emailto[k].slice(emailto[k].indexOf("+") + 1, emailto[k].indexOf("#"));
createToFilter(emailto[k], labelto)
Logger.log(emailto[k]);
Logger.log(labelto);
}
}
}
}
}
}

You can try an email regex (there are many out there), here is one example:
function getTo(email) {
var emailregex = /([a-zA-Z0-9_\.\+-]+#[a-zA-Z0-9-]+\.[a-zA-Z0-9-\.]+)/gm
// Logs the To lines of up to the first 1-500 emails in your Inbox
var threads = GmailApp.getInboxThreads(0, 75);
for (var i = 0; i < threads.length; i++) {
var messages = threads[i].getMessages();
for (var j = 0; j < messages.length; j++) {
var emailto = messages[j].getTo().match(emailregex);
//runs the .to emails through the data conditioning function
//emailprocess(email,emailto)
}
Logger.log(emailto);
}
}

Related

Reexamination of "remove selected items from google form dropdown list"

This clever solution:
remove selected items from google form dropdown list
Removes selected items from google form dropdown list based off of an inventory stored in sheets. The problem is, when I run it I get a "Cannot call method "createChoice" of undefined. (line 39, file "Code")". After thoroughly examining the code, it still seems to me that it should work... Any ideas as to how to fix it?
var LIST_DATA = [{title:"Select a Time", sheet:"Doc Appointments"}];
function updateLists() {
//var form = FormApp.getActiveForm();
var form = FormApp.openById("1fTlfq1ciD2C7iLL7Pw43ld-EyfxxM6GYOF-SdoAkTvw");
var items = form.getItems();
for (var i = 0; i < items.length; i += 1){
for (var j = 0; j < LIST_DATA.length; j+=1) {
var item = items[i];
if (item.getTitle() === LIST_DATA[0].title){
updateListChoices(item.asMultipleChoiceItem(), LIST_DATA[0].sheet);
break;
}
}
}
}
function updateListChoices(item, sheetName){
var inventory = (SpreadsheetApp.openById("1tUpcx4CPu3oMc-A1kMOuE7R3OcfeCPHkHXSpEoam4Xw")
.getSheetByName("Doc Appointments")
.getDataRange()
.getValues());
Logger.log(inventory);
var selected = (SpreadsheetApp.openById("1tUpcx4CPu3oMc-A1kMOuE7R3OcfeCPHkHXSpEoam4Xw")
.getSheetByName("responses")
.getDataRange()
.getValues());
Logger.log(selected);
var choices = [];
var selectedReal = [];
for (var i = 0; i< selected.length; i+=1){
selectedReal.push(selected[i][1])
}
for (var i = 1; i< inventory.length; i+=1){
if(selectedReal.indexOf(inventory[i][0])=== -1){
choices.push(item.createChoice(inventory[i][0]));}
}
if (choices.length < 1) {
var form = FormApp.getActiveForm();
form.setAcceptingResponses(false);
} else {
item.setChoices(choices);
}
}

Turn index match statement into Google Script

I am combining tables from different sheets into one on google sheets. What I am trying to do is set up a function onedit(e) may be combined with a loop function to run this
=index($G$2:$G$8,match($A10&$I$1,arrayformula($B$2:$B$8&$E2:$E8),0),"").
I am new to google script so I have just tried using formulas but the formula updates all cells next to it and what I want is that it matches and stays so that next time column G gets updated then the result be added to B10 instead of rewriting A10. (I1 has formula =today() so that it has a place of reference but if the code can just match with the date then that would be great!)
Here is the link to the sheet if you would like to see what I am talking about. https://docs.google.com/spreadsheets/d/1jviYYhI1V_bL8TMVvijR9vo_7sBFfktbhgblGNcYfrQ/edit?usp=sharing
Column B2:B8 are drop-downs that are based on the list from A10:A18 if that makes any difference.
Any help would be greatly appreciated I've been looking for 3 days and can't find something that would do this.
try this:
function autoload() {
var ss = SpreadsheetApp.getActiveSheet();
var meeting = ss.getRange("B2:F8").getValues();
var targetNames = ss.getRange("A10:A18").getValues();
var writtingRange = ss.getRange("B10:F18").getValues();
var updatedUser = targetNames;
var writtingColumn = -1;
var coolMatrix;
for (var i = 0; i < meeting.length; i++) {
var name = meeting[i][0]
for (var j = 0; j < targetNames.length; j++) {
if (targetNames[j][0] == name) {
for (var z = 0; z < writtingRange[0].length; z++) {
if (writtingRange[j][z] == '' && writtingColumn < 0) {
writtingColumn = z;
break;
}
}
writtingRange[j][writtingColumn] = meeting[i][4];
updatedUser[j] = true;
}
}
}
whiteSpaceRemover(writtingRange);
ss.getRange("B10:F18").setValues(writtingRange);
}
function whiteSpaceRemover(multidimensionalArray) {
for (var i = 0; i < multidimensionalArray.length; i++) {
for (var j = 0; j < multidimensionalArray[0].length; j++) {
if (multidimensionalArray[i][j] == '') {
multidimensionalArray[i].splice(j, 1);
multidimensionalArray[i].push('');
}
}
}
for (var i = 0; i < multidimensionalArray.length; i++) {
if (multidimensionalArray[i][0] == '') {
for (var j = 0; j < multidimensionalArray[i].length; j++) {
if (multidimensionalArray[i][j] != '') {
whiteSpaceRemover(multidimensionalArray);
}
}
}
}
return multidimensionalArray;
}
Tested this with a copy of your sheet, and it was working well, it sets the correct note next to the name and a '-' if they were not in the meeting, you have to run it manually for now, but it can be assigned to an onEdit() if you'd like.
function onEdit(event)
{ var timezone = "GMT-5"; var timestamp_format = "MM/dd/yyyy"; // Timestamp Format.
var updateColName = "Student Name";
var timeStampColName = "Date";
var sheet, ss;
ss = SpreadsheetApp.getActiveSpreadsheet();
sheet = ss.getActiveSheet();//Get the active sheet
var actRng = event.source.getActiveRange();
var editColumn = actRng.getColumn();
var index = actRng.getRowIndex();
var headers = sh
eet.getRange(4, 1, 1, sheet.getLastColumn()).getValues();
var dateCol = headers[0].indexOf(timeStampColName);
var updateCol = headers[0].indexOf(updateColName); updateCol = updateCol+1;
if (dateCol > -1 && index >=5 && index <= 36 && editColumn == updateCol) { // only timestamp if 'Last Updated' header exists, but not in the header row itself!
var cell = sheet.getRange(index, dateCol + 1);
var date = Utilities.formatDate(new Date(), timezone, timestamp_format); cell.setValue(date); }
function onEdit(){
var ss = SpreadsheetApp.getActiveSheet();
var meeting = ss.getRange("B2:F37").getValues();
var targetNames = ss.getRange("A38:A90").getValues();
var writtingRange = ss.getRange("B38:F90").getValues();
var updatedUser = targetNames;
var writtingColumn = -1;
var coolMatrix;
for(var i = 0; i < meeting.length; i++){
var name = meeting[i][0]
for (var j = 0; j < targetNames.length; j++) {
if (targetNames[j][0] == name){
for (var z = 0; z < writtingRange[0].length; z++) {
if (writtingRange[j][z] == '' && writtingColumn < 0) {
writtingColumn = z;
break;
}
}
writtingRange[j][writtingColumn] = meeting[i][4];
updatedUser[j] = true;
}
}
}
for (var w = 0; enter code here w < writtingRange.length; w++){
if (writtingRange[w][writtingColumn] == ''){
writtingRange[w][writtingColumn] = '-';
}
}
ss.getRange("B38:F90").setValues(writtingRange);
}}

javascript nested for loop from a string(multiple layers)

I have a string that I am trying to loop through. It has nested arrays and I want to get the values from each layer. However I seem to be getting an undefined from the second layer onwards.
//String [{"username":"test","usersurname":"test","cellnumber":"test","displayname":"test","profilepicture":"test","projects":[{"projectname":"test","dateadded":"test","notes":"test","image":"test"},{"task":[{"taskname":"test","taskdescription":"test","taskimage":"test"}]}]}]
//My for loop - All variables are declared prior
for(var i = 0; i < data.length; i++){
username = data[i].username;
console.log(username);
usersurname = data[i].usersurname;
cellnumber = data[i].cellnumber;
displayname = data[i].displayname;
profilepicture = data[i].profilepicture;
for(var j = 0; j < data[i].projects.length; j++){
dateadded = data[i].projects[j].dateadded;
console.log(dateadded);
notes = data[i].projects[j].notes;
image = data[i].projects[j].image;
for(var k = 0; k < data[i].projects[j].task.length; k++){
taskname = data[i].projects[j].task[k].taskname;
console.log(taskname);
taskdescription = data[i].projects[j].task[k].taskdescription;
taskimage = data[i].projects[j].task[k].taskimage;
}
}
}
Please check undefined end errors in your code. if something is undefined loop will break.
for (var i = 0; i < data.length; i++) {
username = data[i].username;
console.log(username);
usersurname = data[i].usersurname;
cellnumber = data[i].cellnumber;
displayname = data[i].displayname;
profilepicture = data[i].profilepicture;
if("undefined" != typeof (data[i].projects))
{
for (var j = 0; j < data[i].projects.length; j++) {
dateadded = data[i].projects[j].dateadded;
console.log(dateadded);
notes = data[i].projects[j].notes;
image = data[i].projects[j].image;
if ("undefined" != typeof (data[i].projects[j].task)) {
for (var k = 0; k < data[i].projects[j].task.length; k++) {
taskname = data[i].projects[j].task[k].taskname;
console.log(taskname);
taskdescription = data[i].projects[j].task[k].taskdescription;
taskimage = data[i].projects[j].task[k].taskimage;
}
}
}
}
}

replace string using array in javascript

abc1 abc2 abc3
abc4 abc5 abc6
abc7 abc8 abc9
using above csv file, load text by replacing the double quotes from the bellow sentence.
Sentence:
"" is going with "" to "" for something to know.
Expected out put is:
abc1 is going with abc2 to abc3 for something to know.
abc3 is going with abc5 to abc6 for something to know.
like this in javascript, php.
Code I have tried so far:
var s = 'Neque porro "" estqui "" dolorem';
var insert = [["a1", "b1"]["c1","d1"]];
console.log(insert);
var words = new Array();
words = s.split(" ");
console.log(words);
var count = 0;
for (i = 0; i < words.length; i++) {
for (j = 0; j < insert.length; j++) {
if(words[i] == '""')
s = s.replace(/""/, insert[j]);
}
}
console.log(s);
Hurray I got the answer:
reader.onload = function (e) {
var sent = ''; var sentt = ''; var senttt = '';
sent = $('#mixmsg').val();
var quoteLength = (sent.match(/""/g) || []).length;
var rowcells = [];
rows = e.target.result.split("\n"); alert(rows);
for (var i = 0; i < rows.length; i++) {
var cells = rows[i].split(",");
rowcells.push(cells);
}
var rowcellso = rowcells.slice(0, -1);
console.log(rowcellso);
for (var ro = 0; ro < rowcellso.length; ro++) {
for (var scol = 0; scol < quoteLength; scol++) {
sent = sent.replace(/""/,rowcellso[ro][scol]);
console.log(rowcellso[ro][scol]);
} sentt +=sent+'\n'; sent= $('#mixmsg').val();
}
$('#container').html(sentt);
}

finding and placing a word from the text in an array

I am trying to find a word in the text with my name. The code requires me to first find the first character of the word and then subsequently push the remaining letters in the hits[] array. I am trying but got stuck.
var text = "This is just Rohit.";
var myName = "Rohit";
var hits = [];
for (var i = 0; i < text.length; i++)
{
if(text[i] === myName[0] )
{
for(j = 0; j < myName.length; j++)
{
hits.push(text[i]);
};
};
};
hits;
var text = "This is just Rohit.";
var myName = "Rohit";
var hits = [];
for (var i = 0; i < text.length; i++) {
if(text[i] === myName[0] ) {
for(var j = i, l = 0; l < myName.length; j++, l++) {
hits.push(text[j]);
}
}
}
console.log(hits.join(''));
Just ignore the searchtext and go with the searchterm.
var hits = [];
var i=0;
while (i<"Rohit".length) arr.push("Rohit"[i++]);
console.log(hits);
// ["R", "o", "h", "i", "t"]
Something like this should help.Let me know if a change is needed.
var text = "This is just Rohit.";
var myName = "Rohit.";
var hits = [];
var array1=text.split(" ");
for (var i = 0; i < array1.length; i++)
{
if(array1[i]==myName)
{
hits.push(array1[i].split(''));
}
}
THIS PART IS THE METHOD WHICH YOU WERE USING::
var text = "This is just Rohit.";
var myName = "Rohit";
var hits = [];
var x='';
for (var i = 0; i < text.length; i++)
{
if(text[i] === myName.charAt(0) && text[i-1]==" " )
{
for(j = i; j < (i+myName.length); j++)
{
console.log(text[j]);
x=x+text[j];
}
}
}
hits[0]=x;
alert(hits);
After looking at your comments for clarification, it looks like you just want your name as the only element in a new array.
Use this:
var text = 'Your name is Rohit.';
var name = 'Rohit';
var hits = [text.substring(text.indexOf(name), text.indexOf(name) + name.length)];
console.log(hits);
// ["Rohit"]
Can't imagine how this is helpful, but the code above will do what you want.
I solved it.
var text = "This is just Rohit.";
var myName = "Rohit";
var hits = [];
for (var i = 0; i < text.length; i++)
{
if(text[i] === myName[0] )
{
for(var j = i; j < (myName.length+i); j++)
{
hits.push(text[j]);
};
};
};
hits;

Categories