Get email from Google Docs - javascript

I actually wanted to send MoM on daily basis, so I created a folder where I put all MoM docs and title them with the date for which it was created. Then script reads it on the day and send it to fixed email address, but now we inserted the attendees inside the google docs like this :-
Is there any way I can get those email address/user email address mentioned there.
Script I was using earlier was this :-
function sendMinutes() {
const folder = DriveApp.getFolderById('Filder id')
const today = Utilities.formatDate(new Date(),Session.getScriptTimeZone(),'MMM dd,yyyy')
const files = folder.searchFiles(`title contains '${today}'`)
while(files.hasNext())
{
let file= files.next()
let doc = DocumentApp.openById(file.getId())
let body = doc.getBody()
let parag = body.getParagraphs().forEach(r=> {
.....
})
}
}
I got how to get email but, it is just returning first email now, i need to get every email address as ElementType as PERSON:-
body.findElement(DocumentApp.ElementType.PERSON).getElement().asPerson().getEmail()
Thanks

Body.findElement has several forms, one of them use two parameters, the second one is the start point for finding the next element. Use this method form together with a loop. In the following example a while statement is being used:
function logEmailsFromPersonChips() {
const doc = DocumentApp.getActiveDocument();
const body = doc.getBody();
let found;
const emails = [];
while ( found = body.findElement(DocumentApp.ElementType.PERSON,found)){
const email = found.getElement().asPerson().getEmail();
emails.push(email);
}
console.log(JSON.stringify(emails))
}

Related

How to put data currently in a const object within the script in a separate file?

I have a program that takes in parameters from a form and uses them to generate a narrative comment (meant for teachers that need to write narrative comments on grade reports):
const sentences = {
"participation": "engages productively in class discussions",
"assignments": "completes all assignments on time",
"mastery": "shows excellent understanding of the content on all assessments"
}
function writeComment(event) {
event.preventDefault();
let name = document.getElementById('name').value;
let schoolClass = document.getElementById('schoolClass').value;
let term = document.getElementById('term').value;
let strength1 = sentences[document.getElementById('strength1').value];
let strength2 = sentences[document.getElementById('strength2').value];
let result = `It has been wonderful having ${name} in ${schoolClass} during the ${term} term!
${name} ${strength1}. ${name} ${strength2}`
document.getElementById('result').innerText = result;
}
I'd like to store const sentences in a separate file, with other similar objects, that the current script would read from and use to populate the result. Is there a way to do that? I've tried storing it in a json file and using fetch on a local server but I wasn't able to actually make the data accessible to the script.

Invalid argument: replacement error when populating google doc using google script

I have written a code to populate data from a spreadsheet into a google doc and save it to drive using g-sript. Here is the code for the same :
function onOpen() {
const ui = SpreadsheetApp.getUi();
const menu = ui.createMenu('Invoice creator');
menu.addItem('Generate Invoice', 'invoiceGeneratorFunction');
menu.addToUi();
}
function invoiceGeneratorFunction() {
const invoiceTemplate = DriveApp.getFileById('125NPu-n77F6N8hez9w63oSzbWrtryYpRGOkKL3IbxZ8');
const destinationFolder = DriveApp.getFolderById('163_wLsNGkX4XDUiSOcQ88YOPe3vEx7ML');
const sheet_invoice = SpreadsheetApp.getActiveSpreadsheet().getSheetByName('New Invoice Sheet');
const rows = sheet_invoice.getDataRange().getValues();
Logger.log(rows);
rows.forEach(function(row, index) {
if (index === 0) return;
if (row[12] != "") return;
const copy = invoiceTemplate.makeCopy(`${row[1]} VIN Number: ${row[2]}`,destinationFolder);
const doc = DocumentApp.openById(copy.getId());
const body = doc.getBody();
var friendlyDateBilled = new Date(row[0]).toLocaleDateString();
var friendlyDateDelivery = new Date(row[3]).toLocaleDateString();
body.replaceText('{{Date Billed}}',friendlyDateBilled);
body.replaceText('{{Customer Name}}',row[1]);
body.replaceText('{{VIN Number}}',row[2]);
body.replaceText('{{Date of Delivery}}',friendlyDateDelivery);
body.replaceText('{{Package}}',rows[4]);
body.replaceText('{{Price}}',rows[5]);
body.replaceText('{{Output CGST}}',rows[6]);
body.replaceText('{{Output SGST}}',rows[7]);
body.replaceText('{{Discount}}',rows[8]);
body.replaceText('{{Total Price}}',rows[9]);
body.replaceText('{{Balance}}',rows[10]);
body.replaceText('{{Remarks}}',rows[11]);
doc.saveAndClose();
const url = doc.getUrl();
sheet_invoice.getRange(index+1, 13).setValue(url);
})
}
I have created a menu button for the script to run. But when i run it I get an error saying :
Exception: Invalid argument: replacement
at unknown function
at invoiceGeneratorFunction(Code:17:8)
(Here line 32 is body.replaceText('{{Package}}',rows[4]);
and line 17 is the start of forEach)
Interestingly when I comment out the rest of body.replaceText lines after that line, the code works. I can't understand what the problem is, if it's working if I comment out the lines.
In your script, rows is 2 dimensional array retrieved with sheet_invoice.getDataRange().getValues(). When I saw your loop, after the line of body.replaceText('{{Package}}',rows[4]);, rows is used. In this case, rows[4] is 1-dimensional array. It is required to be the string for the arguments of replaceText(searchPattern, replacement). I think that this might be the reason for your issue. In order to remove this issue, how about the following modification?
From:
body.replaceText('{{Package}}',rows[4]);
body.replaceText('{{Price}}',rows[5]);
body.replaceText('{{Output CGST}}',rows[6]);
body.replaceText('{{Output SGST}}',rows[7]);
body.replaceText('{{Discount}}',rows[8]);
body.replaceText('{{Total Price}}',rows[9]);
body.replaceText('{{Balance}}',rows[10]);
body.replaceText('{{Remarks}}',rows[11]);
To:
body.replaceText('{{Package}}',row[4]);
body.replaceText('{{Price}}',row[5]);
body.replaceText('{{Output CGST}}',row[6]);
body.replaceText('{{Output SGST}}',row[7]);
body.replaceText('{{Discount}}',row[8]);
body.replaceText('{{Total Price}}',row[9]);
body.replaceText('{{Balance}}',row[10]);
body.replaceText('{{Remarks}}',row[11]);
Note:
I'm not sure about your actual values of rows. So I'm not sure whether the values of row[4] to row[11] are what you want. If those values are not the values you expect, please check your Spreadsheet again.
Reference:
replaceText(searchPattern, replacement)

Extract some google email information into google spreadsheet

Hi following the question in this thread Google Script to pull certain information from email and put in a Sheet
I am really interested to understand if is it possible to extract multiple parts of the email.
For example, if I have two different blocks inside my email like
Item#: SS10MM
Product Description: 10mm SOCKET
Vendor: Store
Vendor Item Code: 10MSS
Complaint: Lost another one, really wish you could put a GPS chip in these!
may I extract both?
thanks a lot
var LABEL_PENDING = "pending";
var LABEL_DONE = "done";
// processPending(sheet)
// Process any pending emails and then move them to done
function processPending_(sheet) {
// 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].getPlainBody();
Logger.log(message);
// Process the messages here
message = message.substr(message.search("Item#:")); //Get the beginning of the important part + cut off the beginning
Logger.log(message);
message = message.split("\n");
Logger.log(message[0].split(": ")[1]);
var data = [message[0].split(": ")[1], //Item#
message[1].split(": ")[1], //Prod. Desc.
message[2].split(": ")[1], //Vendor
message[3].split(": ")[1], //Ven. Item Code
message[4].split(": ")[1] //Complaint
];
// Add message to sheet
sheet.appendRow(data);
// Set to 'done' by exchanging labels
thread.removeLabel(label_pending);
thread.addLabel(label_done);
}
}

Can I use Google Apps Script to export specific information from a recurring email via Gmail?

I'd like a script to find emails with a specific subject line and then find information within that email and export it to a doc, spreadsheet or email it to myself as plain text.
We get orders, via email, for printed clothing.
Subject:Your t-shirt order
Body:
Name to print: James
Name to print: Steve
Name to print: Ryan
I'd love a method to get all the names, on their own, to copy and paste them to Adobe Illustrator and set them up for print.
To save Gmail messages to a Google Spreadsheet, you need to specify the Gmail search query and the sheet ID where the matching messages are to be exported.
Found this sample code from this tutorial.
var SEARCH_QUERY = "label:inbox is:unread to:me";
// Credit: https://gist.github.com/oshliaer/70e04a67f1f5fd96a708
function getEmails_(q) {
var emails = [];
var threads = GmailApp.search(q);
for (var i in threads) {
var msgs = threads[i].getMessages();
for (var j in msgs) {
emails.push([msgs[j].getBody().replace(/<.*?>/g, '\n')
.replace(/^\s*\n/gm, '').replace(/^\s*/gm, '').replace(/\s*\n/gm, '\n')
]);
}
}
return emails;
}
function appendData_(sheet, array2d) {
sheet.getRange(sheet.getLastRow() + 1, 1, array2d.length, array2d[0].length).setValues(array2d);
}
function saveEmails() {
var array2d = getEmails_(SEARCH_QUERY);
if (array2d) {
appendData_(SpreadsheetApp.getActiveSheet(), array2d);
}
}
You can also check this related forum and tutorial.

Alfresco: Javascript data list creation

I am attempting to execute some Javascript in my Alfresco workflow to create a custom data list type in my site called "Testing". But before I fill in my custom data list type information, I tried simply creating a contact list data list based on examples I found to make sure it works.
Here is my code:
var site = siteService.getSite("Testing");
var dataLists = site.childByNamePath("dataLists");
if (!dataLists) {
var dataLists = site.createNode("dataLists", "cm:folder");
var dataListProps = new Array(1);
dataListProps["st:componentId"] = "dataLists";
dataLists.addAspect("st:siteContainer", dataListProps);
dataLists.save();
logger.log("Created new datalists folder.");'
}
var contactList = dataLists.childByNamePath("contactlist1");
if (!contactList) {
var contactList = dataLists.createNode("contactlist1","dl:dataList");
// tells Share which type of items to create
contactList.properties["dl:dataListItemType"] = "dl:contact";
contactList.save();
var contactListProps = [];
contactListProps["cm:title"] = "My Contacts";
contactListProps["cm:description"] = "A contact list generated by a javascript.";
contactList.addAspect("cm:titled", contactListProps);
logger.log("Created contact datalist.");
}
var contact = contactList.createNode(null, "dl:contact")
contact.properties["dl:contactFirstName"] = "Florian";
contact.properties["dl:contactLastName"] = "Maul";
contact.properties["dl:contactEmail"] = "info#fme.de";
contact.properties["dl:contactCompany"] = "fme AG";
contact.properties["dl:contactJobTitle"] = "Senior Consultant";
contact.properties["dl:contactPhoneMobile"] = "not available";
contact.properties["dl:contactPhoneOffice"] = "not available";
contact.properties["dl:contactNotes"] = "Alfresco Expert";
contact.save();
logger.log("Created new contact: " + contact.nodeRef);
My guess is it's not selecting the right site, but I'm not sure how else to set the site variable to the "Testing" site. Also, I know this code is in the right place in my .bpmn file, because other Javascript in there executes correctly.
What is wrong with my code?
There are 2 javascript object on which you have confusion.One is site and other is node.Site object does not have method called childByNamePath.
Instead of that use below for getting datalist.
var dataLists = site.getContainer("dataLists");
Your code for retrieving site is correct.The only change is for datalist.

Categories