Google Script to format information pulled through script - google-apps-script

the following script below will read my email and pull a value from an email as well as the recipient of the message. I'm looking to add to the code in which I just get the email address for the recipient.
Currently, the code will process: John Doe *** john.doe#gmail.com ****
- I just want the code to pull john.doe#gmail.com, without the arrow bracket symbols
Any insight on where to add this is greatly appreciated!
// Modified from http://pipetree.com/qmacro/blog/2011/10/automated-
email-to-task-mechanism-with-google-apps-script/
// Globals, constants
var LABEL_PENDING = "example label/PENDING";
var LABEL_DONE = "example label/DONE";
// processPending(sheet)
// Process any pending emails and then move them to done
function processPending_(sheet) {
// Date format
var d = new Date();
var date = d.toLocaleDateString();
// Get out labels by name
var label_pending = GmailApp.getUserLabelByName(LABEL_PENDING);
var label_done = GmailApp.getUserLabelByName(LABEL_DONE);
// The threads currently assigned to the 'pending' label
var threads = label_pending.getThreads();
// Process each one in turn, assuming there's only a single
// message in each thread
for (var t in threads) {
var thread = threads[t];
// Gets the message body
var message = thread.getMessages()[0].getBody();
var recipient = thread.getMessages()[0].getTo();
// Processes the messages here
orderinfo = message.split("example");
rowdata = orderinfo[1].split(" ");
// Add message to sheet
sheet.appendRow([rowdata[1], recipient]);
// Set to 'done' by exchanging labels
thread.removeLabel(label_pending);
thread.addLabel(label_done);
}
}
// main()
// Starter function; to be scheduled regularly
function main_emailDataToSpreadsheet() {
// Get the active spreadsheet and make sure the first
// sheet is the active one
var ss = SpreadsheetApp.getActiveSpreadsheet();
var sh = ss.setActiveSheet(ss.getSheets()[0]);
// Process the pending emails
processPending_(sh);
}

Regarding your last error message:
var LABEL_PENDING = "example label/PENDING";
var LABEL_DONE = "example label/DONE";
script will search labels with the name: "example label/PENDING" and "example label/DONE". Are you sure that you have the label with name "example label/PENDING" or "example label/DONE"?
Here is a little bit modified code based on your example. You just need to create label "PENDING" and mark some messages with this label.
var LABEL_PENDING = "PENDING";
function processPending () {
var sheet = SpreadsheetApp.getActive().getActiveSheet();
// Date format
var d = new Date();
var date = d.toLocaleDateString();
// Get out labels by name
var label_pending = GmailApp.getUserLabelByName(LABEL_PENDING);
// The threads currently assigned to the 'pending' label
var threads = label_pending.getThreads();
// Process each one in turn, assuming there's only a single
// message in each thread
for (var i = 0; i <threads.length; i++) {
var thread = threads[i];
// Gets the recipient
var recipient = thread.getMessages()[0].getTo();
// Add recipient to sheet
sheet.appendRow([recipient]);
}
}

Related

Need to Copy data from email and paste into google spreadsheet

There was two function wrote in that answer code, one is main and another one is extract details so its take two function, whenever ran the script its throwing error like getdate() not define so i just make as one function as main, now the data tracked automatically into sheet but its reading only first thread which is unread label. if the label having 23 thread , the first thread only repeating as 23 times. even I Have changed threads.messages(0) tracking only first thread which is already read thread, not read and track unread thread. Could you help me
function main(){
var query = {'q':'label:"Sanmina EDI Failed Concurrent Jobs Alert" is:UNREAD'};
var threads = Gmail.Users.Messages.list(userId='me', q=query);
for(i in threads.messages){
var threadIds = threads.messages[0].threadId;
var message = GmailApp.getMessageById(threadIds);
extractDetails(message);
GmailApp.markMessageRead(message);
}
function extractDetails(message)
{
var dateTime = message.getDate();
var bodyContents = message.getBody();
var action= bodyContents.search("Invoice")
var action1=bodyContents.search("Error")
var action2=bodyContents.search("Terminated")
if(action > 0)
{
var out="Need to create SR"
}
else if(action1>0 || action2>0)
{
var out="Need to create SR"
}
else
{
var out="Printing output file"
}
var activeSheet = SpreadsheetApp.getActiveSpreadsheet().getActiveSheet();
activeSheet.autoResizeRows(1, 2);
activeSheet.appendRow([dateTime, bodyContents, out]);
}
}
[enter image description here][1]
Sanmina EDI Failed Concurrent Jobs Alert - subject same name for label
Production Workflow Mailer
May 26, 2017, 7:30 PM
Request Id Program Name Status Requested By
---------- ------------------------------------------------------------ -------- 813511350 Sanmina EDI 850/860 Inbound PO/Change Tabular Report Warning NERODRIG
Try using the Gmail API to search the threads:
function main(){
var query = {'q':'label:"Sanmina EDI Failed Concurrent Jobs Alert" is:UNREAD'};
var threads = Gmail.Users.Messages.list(userId='me', q=query);
for(i in threads.messages){
var threadIds = threads.messages[i].threadId;
var message = GmailApp.getMessageById(threadIds);
extractDetails(message);
GmailApp.markMessageRead(message);
}
}
function extractDetails(message){
var dateTime = message.getDate();
var bodyContents = message.getPlainBody();
var action= bodyContents.search("Invoice")
var action1=bodyContents.search("Error")
var action2=bodyContents.search("Terminated")
if(action > 0)
{
var out="Need to create SR"
}
else if(action1>0 || action2 > 2)
{
var out="Need to create SR"
}
else
{
var out="Printing output file"
}
var activeSheet = SpreadsheetApp.getActiveSpreadsheet().getActiveSheet();
activeSheet.appendRow([dateTime, bodyContents, out]);
}
In case you only want the last message, use threads.messages[0] instead of i.
More information:
List method

Send email when cell contains a specific value

I am working on a Google Form that allows our employees to submit an in-field inspection of their equipment. I have a script that takes the form responses and creates a new sheet based on the date and the specific unit number of the equipment. The user goes through a checklist and selects either "Good" or "Needs Repair" for each item on the list. They can also add comments and upload pictures of any issues.
I am trying to have the script automatically send an email if "Needs Repair" is selected for any of the checks, as well as if the user adds a comment or a picture. This way we do not have to open every submitted sheet to know if any repairs are required. What I have is just not sending emails and I cannot figure out why. Any help is greatly appreciated!
Here is my current script:
function onFormSubmit() {
// onFormSubmit
// get submitted data and set variables
var ss = SpreadsheetApp.openById("*Spreadsheet Link*");
var sheet = ss.getSheetByName("Submissions");
var row = sheet.getLastRow();
var Col = sheet.getLastColumn();
var headings = sheet.getRange(1,1,1,Col).getValues();
var lastRow = sheet.getRange(row, 1, 1, Col);
var UnitNumber = sheet.getRange(row,3).getValue();
var newSheet = sheet.getRange(row,4,Col).getValue();
var fileExist = false;
var drillSheet = null;
var folder = DriveApp.getFoldersByName("Fraser Drill Inspections").next();
var files = folder.getFilesByName(UnitNumber);
var file = null;
var employee = sheet.getRange(row,2);
var checks = sheet.getRange(row, Col, 1, 20);
// check if Drill has sheet
while (files.hasNext())
{
fileExist = true;
file = files.next();
break;
}
if (fileExist) //If spreadsheet exists, insert new sheet
{
drillSheet = SpreadsheetApp.openById(file.getId());
drillSheet.insertSheet("" + newSheet);
}
else //create new spreadsheet if one doesn't exist
{
drillSheet = SpreadsheetApp.create(UnitNumber);
var ssID = drillSheet.getId();
file = DriveApp.getFileById(ssID);
file = file.makeCopy(UnitNumber, folder);
DriveApp.getFileById(ssID).setTrashed(true);
drillSheet = SpreadsheetApp.openById(file.getId());
drillSheet.renameActiveSheet(newSheet);
}
// copy submitted data to Drill sheet
drillSheet.getSheetByName(newSheet).getRange(1,1,1,Col).setValues(headings);
drillSheet.appendRow(lastRow.getValues()[0]);
drillSheet.appendRow(['=CONCATENATE(B6," ",B5)']);
drillSheet.appendRow(['=TRANSPOSE(B1:2)']);
//Hide top rows with raw data
var hiderange = drillSheet.getRange("A1:A3");
drillSheet.hideRow(hiderange);
//Widen columns
drillSheet.setColumnWidth(1,390);
drillSheet.setColumnWidth(2,700);
//Send email if there are any comments or if anything needs repair
if(lastRow.getValues() == "Needs Repair") {
function SendEmail() {
var ui = SpreadsheetApp.getUi();
MailApp.sendEmail("email#domain.com", "Drill Needs Repair", "This drill requires attention according to the most recent inspection report.")
}
}
}
The function to send an email is:
GmailApp.sendEmail(email, subject, body);
Try changing
if(lastRow.getValues() == "Needs Repair") {
function SendEmail() {
var ui = SpreadsheetApp.getUi();
MailApp.sendEmail("email#domain.com", "Drill Needs Repair", "This drill requires attention according to the most recent inspection report.")
}
}
to just the following:
if(lastRow.getValues() == "Needs Repair") {
GmailApp.sendEmail("youremail#domain.com", "Drill Needs Repair", "This drill requires attention according to the most recent inspection report.");
}
It looks like you've still got some additional work to do too, e.g. to make it send to the email address from the form submission instead of a hardcoded one.

google script to pull recipient of an email in a label

I have automatic email alerts that go into a label in my inbox (through the reply-to) and are also sent to users (through the to: part of the email).
I'm looking to add onto my script that pulls information in the body of the email. Ultimately, I want to pull the recipient of the email (in the to: part) and put that in Column B of a google sheet. Any insight will be greatly appreciated.
Script:
// Modified from http://pipetree.com/qmacro/blog/2011/10/automated-email-to-task-mechanism-with-google-apps-script/
// Globals, constants
var LABEL_PENDING = "Example label/PENDING";
var LABEL_DONE = "Example label/DONE";
// processPending(sheet)
// Process any pending emails and then move them to done
function processPending_(sheet) {
// Date format
var d = new Date();
var date = d.toLocaleDateString();
// Get out labels by name
var label_pending = GmailApp.getUserLabelByName(LABEL_PENDING);
var label_done = GmailApp.getUserLabelByName(LABEL_DONE);
// The threads currently assigned to the 'pending' label
var threads = label_pending.getThreads();
// Process each one in turn, assuming there's only a single
// message in each thread
for (var t in threads) {
var thread = threads[t];
// Gets the message body
var message = thread.getMessages()[0].getBody();
// Processes the messages here
orderinfo = message.split("example split");
rowdata = orderinfo[1].split(" ");
// Add message to sheet
sheet.appendRow([rowdata[1]]);
// Set to 'done' by exchanging labels
thread.removeLabel(label_pending);
thread.addLabel(label_done);
}
}
// main()
// Starter function; to be scheduled regularly
function main_emailDataToSpreadsheet() {
// Get the active spreadsheet and make sure the first
// sheet is the active one
var ss = SpreadsheetApp.getActiveSpreadsheet();
var sh = ss.setActiveSheet(ss.getSheets()[0]);
// Process the pending emails
processPending_(sh);
}
You can access the recipient data with the getTo() function of the message. You could simply add a line that saves itin the column
//Gets the message body and recipent
var message = thread.getMessages()[0].getBody();
var recipient = thread.getMessages()[0].getTo();
//...
// Add message and recipient to sheet
sheet.appendRow([rowdata[1], recipient]);
More info on the function of the gmailMessage class -> https://developers.google.com/apps-script/reference/gmail/gmail-message

How to check Gmail Thread for Replies from Email

I am creating a basic CRM that needs to mark when a thread has been replied to.
I have created a script that can scan my inbox for threads from a list of emails in a sheet, check the last message in each thread and collect the .getFrom in order to see if I was the last to reply.
However, I can't figure out how to check if there has been a response from the person who's been contacted throughout the whole thread.
Here's the script that checks for the last message. (It's an extract of a larger script in case any references are missing):
Example Sheet
function UpdateStatus() {
// Connect to our active sheet and collect all of our email addresses in column G
var sheet = SpreadsheetApp.getActiveSheet();
var totalRows = sheet.getLastRow();
var range = sheet.getRange(2, COLUMN_WITH_EMAIL_ADDRESSES, totalRows, 1);
var emails = range.getValues();
// Attempt to iterate through 100 times (although we'll timeout before this)
for (var cntr = 0; cntr<100; cntr++ ) {
// If we've reached the end of our last, wrap to the front
if (lastRowProcessed >= totalRows) lastRowProcessed = 1;
// Increment the row we're processing
var currentRow = lastRowProcessed+1;
// Get the email address from the current row
var email = emails[currentRow-2][0];
// If the email address field is empty, skip to the next row
if (!email) {
lastRowProcessed = currentRow;
cache.put("lastRow", currentRow, 60*60*24);
continue;
}
// Look for all threads from me to this person
var threads = GmailApp.search('from:me to:'+email);
// If there are no threads, I haven't emailed them before
if (threads.length == 0) {
// Update the spreadsheet row to show we've never emailed
var range = sheet.getRange(currentRow,13, 1, 4 ).setValues([["NEVER", "", "", ""]] );
// And carry on
lastRowProcessed = currentRow;
cache.put("lastRow", currentRow, 60*60*24); // cache for 25 minutes
continue;
}
// Beyond a reasonable doubt
var latestDate = new Date(1970, 1, 1);
var starredMsg = "";
var iReplied = ""
// Iterate through each of the message threads returned from our search
for (var thread in threads) {
// Grab the last message date for this thread
var threadDate = threads[thread].getLastMessageDate();
// If this is the latest thread we've seen so far, make note!
if (threadDate > latestDate) {
latestDate = threadDate;
// Check to see if we starred the message (we may be back to overwrite this)
if (threads[thread].hasStarredMessages()) {
starredMsg = "★";
} else {
starredMsg = "";
}
// Open the thread to get messages
var messages = threads[thread].getMessages();
// See who was the last to speak
var lastMsg = messages[messages.length-1];
var lastMsgFrom = lastMsg.getFrom();
// Use regex so we can make our search case insensitive
var re = new RegExp(email,"i");
// If we can find their email address in the email address from the last message, they spoke last
// (we may be back to overwrite this)
if (lastMsgFrom.search(re) >= 0) {
iReplied = "NO";
} else {
iReplied = "YES";
}
}

Templated email using Apps Script based on data in Google Sheets

I'm new to scripting so I hope someone can help me create one.
I'm trying to create a script for a sheet that can send an email when a custom menu is pressed.
Here's a file to work on.
https://docs.google.com/spreadsheets/d/1Ea-3eZoclHrAkZLwRmWWFbmbnn4dESNWvK_6pn1DCbE/edit?usp=sharing
Also, it should only send it if a column (ex. Column I) has a specific Value like 'Approved'
Email content should look like:
Subject: Leave Application # 'ColumnC'
Hi 'ColumnA',
We received your 'ColumnB' request for 'ColumnE'
Status: 'ColumnG'
More Details: 'ColumnH'
-Admin
Email should be sent to Column E and F.
The script must also update the spreadsheet to avoid duplicate emails.
Here is the working example
Here is the code:
function sendEmails() {
var sheet = SpreadsheetApp.getActiveSpreadsheet();
var startRow = 2; // First row of data to process
var lastRow = sheet.getSheetByName('Journal').getLastRow(); // Last row with content
var rangeEmailSent = sheet.getRangeByName('Journal!EmailSent');
var dataEmailSent = rangeEmailSent.getValues();
var dataRequestedBy = sheet.getRangeByName('Journal!RequestedBy').getValues();
var dataRequestType = sheet.getRangeByName('Journal!RequestType').getValues();
var dataRefNo = sheet.getRangeByName('Journal!RefNo') .getValues();
var dataStatus = sheet.getRangeByName('Journal!Status') .getValues();
var dataToEmail = sheet.getRangeByName('Journal!ToEmail') .getValues();
var dataSupComment = sheet.getRangeByName('Journal!SupervisorComment').getValues();
var subjectTemplate = sheet.getRangeByName('SubjectTemplate1').getValue();
var bodyTemplate = sheet.getRangeByName('BodyTemplate1').getValue();
var msgSubject;
var msgBody;
for (var i = (startRow-1); i <= (lastRow-1); i++) {
// send e-mail if "Email Sent" is not blank and if "Status" is not empty
if ( !(dataEmailSent[i]=='Yes') && !(dataStatus[i] =='')) {
msgSubject = subjectTemplate.replace('$REF$', dataRefNo[i]);
msgBody = bodyTemplate
.replace('$REQUESTED_BY$', dataRequestedBy[i])
.replace('$REQUEST_TYPE$', dataRequestType[i])
.replace('$EMAIL$', dataToEmail[i])
.replace('$STATUS$', dataStatus[i])
.replace('$SupervisorComment$', dataSupComment[i]);
// Logger.log(msgSubject);
// Logger.log(msgBody);
MailApp.sendEmail(dataToEmail[i], msgSubject, msgBody);
// Change "Email sent" to "Yes"
rangeEmailSent.getCell(i+1,1).setValue('Yes'); // note: getCell(1,1) refers to the 1st cell
}
}
}