Google Contacts Fields to fill variables in email template - email

First of all, thank you for your time.
I have been looking for a while for a program, a script or anything that could help me automate a task that otherwise is going to take very long.
See, i'm a french computer technician working for almost exclusively doctors here in France.
The doctors receive results by email, the results are then imported to the patient's folder from the email automatically.
But in order for them to receive that information we have to communicate an email address from a special domain + the doctor's ID that is like your driver's ID.
We use google contact as an address book because it's convenient. Since whenever we make a new maintenance contract with a doctor we input everything to google contact the info is already there. Sometimes we have up to 20 doctors in the same cabinet to set.
Link to a Google Sheet Contact Sample
The fields are the following :
Structure's Name : {{contact company name}} (all the doctors share the same structure)
Strutre's Adress : {{contact full address}} (all the doctors share the same structure)
First doctor
Last Name : {{last_name}}
First Name : {{first_name}}
eMail Address : {{email_address}} (this one is tagged MSSANTE in ggC)
Doc's ID : {{custom_field}} (this is a custom field tagged RPPS in ggC)
Second doctor
Last Name : {{last_name}}
First Name : {{first_name}}
eMail Address : {{email_address}} (this one is tagged MSSANTE in ggC)
Doc's ID : {{custom_field}} (this is a custom field tagged RPPS in ggC)
So on and so on.
Then this as to be sent to many laboratories all in BCC and the customers/doctors usually in CC
I was thinking of using google sheets or google's people API somehow...
Can someone give me a strategy or some code to start ?
Again thanks to anyone who can help even a bit.

Try
function email() {
const ss = SpreadsheetApp.getActiveSpreadsheet()
const emails = ss.getSheetByName('LABS mails').getRange('C2:C').getValues().flat().filter(r => r != '').join(',')
MailApp.sendEmail({
to: emails,
subject: 'titre du mail',
htmlBody: body()
})
}
function body() {
const ss = SpreadsheetApp.getActiveSpreadsheet()
const template = ss.getSheetByName('Mail Template (Exemple)')
const docteurs = ss.getSheetByName('Doctors')
let [headers, ...data] = docteurs.getDataRange().getDisplayValues()
let debut = template.getRange('A2:A').getValues().flat().filter(r => r != '').join('<br>')
let variable = template.getRange('B2:B').getValues().flat().filter(r => r != '').join('<br>')
let fin = template.getRange('C2:C').getValues().flat().filter(r => r != '').join('<br>')
const liste = ['{CABINET}', '{NOM}', '{PRENOM}', '{EMAIL}', '{RPPS}']
const colonnes = [1,4,3,8,7]
let message = debut
data.forEach((r, row) => {
var texte = variable
for (var i = 0; i < liste.length; i++) {
texte = texte.replace(liste[i], r[+colonnes[i] - 1])
}
message += texte + '<br><br>'
})
message += fin
return (message)
}
Put the text as follows (you will need a little html tags)
The email will be

Related

How to "clip" similar emails and import only part of them in Google Sheets

I use a script to import the body of emails to a sheet.
This is the part of the script that imports the body of emails to a sheet
var newReceipts = [];
for (var i = 0; i < foundThreads.length; i++) {
var messages = foundThreads[i].getMessages();
for (var m = 0; m < messages.length; m++) {
var subject = messages[m].getSubject(); //subject field
var body = messages[m].getPlainBody(); //body field
var from = messages[m].getFrom(); //from field
newReceipts.push([subject,body,from]);
A sample text (body) would be:
some text I need to keep,
more text I need....
Did you know that:
bla bla bla and more and more I DON'T need
Another email could be:
Our meeting will take place on Monday
Did you know that:
You cannot be late?
A third email could be:
There is great strain in our group.
The following people please report to the human resources department.
John
Mary
Paul
Did you know that:
A raise is coming next month?
Pay increases tend to vary based on inflation, location, sector, and job performance.
Most employers give their employees an average increase of 3% per year.
Consistent job switching may have an impact on the rate at which your salary increases.
So, there is always a top part, followed by the constant Did you know that:, followed by a bottom part.
I only need to keep the top part of the email before the Did you know that:
In your situation, how about the following sample script?
Sample script:
const check = "Did you know that";
const sample1 = `some text I need to keep,
more text I need....
Did you know that:
bla bla bla and more and more I DON'T need`;
const sample2 = `Our meeting will take place on Monday
Did you know that:
You cannot be late?`;
const sample3 = `There is great strain in our group.
The following people please report to the human resources department.
John
Mary
Paul
Did you know that:
A raise is coming next month?
Pay increases tend to vary based on inflation, location, sector, and job performance.
Most employers give their employees an average increase of 3% per year.
Consistent job switching may have an impact on the rate at which your salary increases.`;
const values = [sample1, sample2, sample3];
const res = values.map(e => e.includes(check) ? e.split(check)[0].trim() : "");
console.log(res)
When this script is run, the following result is obtained.
[
"some text I need to keep, \nmore text I need....",
"Our meeting will take place on Monday",
"There is great strain in our group.\nThe following people please report to the human resources department.\nJohn\nMary\nPaul"
]
When the value of check is not included in the text, "" is returned.
When your showing script is modified, how about the following modification?
var newReceipts = [];
for (var i = 0; i < foundThreads.length; i++) {
var messages = foundThreads[i].getMessages();
for (var m = 0; m < messages.length; m++) {
var subject = messages[m].getSubject(); //subject field
var body = messages[m].getPlainBody(); //body field
// --- Added
const check = "Did you know that";
if (body.includes(check)) {
body = body.split(check)[0].trim();
}
// ---
var from = messages[m].getFrom(); //from field
newReceipts.push([subject,body,from]);
References:
split()
replace()

Google Form Get Last responses

I can't understand why Google Form is returning me not the last responses, but the penultimate one after I run an OnSubmit script. Let me explain better, I intend to intercept the user's responses and when sending the form to propose a link pre-filled with his last answers given that he can modify and postpone.
function getLastFormResponse(form = FormApp.getActiveForm()) {
form.getResponses()
.pop()
.getItemResponses()
.forEach((itemResponse) => {
this[itemResponse.getItem().getTitle()] = itemResponse.getResponse();
}
);
}
const formResponse = new getLastFormResponse();
const name = formResponse['NAME'];
Logger.log(name);
const surname = formResponse['SURNAME'];
Logger.log(surname);
const age = formResponse['AGE'];
Logger.log(age);
const reserved_room = formResponse['RESERVED_ROOM'];
Logger.log(reservedRoom);
var constructionLink = ('https://docs.google.com/forms/d/e/1FAIpQLScgu1FWB6-tQjpviyr9_dZetd2SKdqZZmsL_Imp30nWYqsq7g/viewform?usp=pp_url&entry.81904614='+name+'&entry.1534059913='+surname+'&entry.181893772='+age+'&entry.772338055='+reservedRoom);
Logger.log(constructionLink);
Logger.log(JSON.stringify(formResponse,null,2));
form = FormApp.getActiveForm();
form.setConfirmationMessage('Thanks for your feedback !!'+ constructionLink )
So, when the user press Submit button, a link comes out pre-filled with the "latest" information present... but, in reality, not the last (before the submit) but the penultimate ones are taken from corresponding spreadsheet ...
I would like to get the latest that he filled out.

How to get email form submissions script to exclude blank response values from sheet?

I am editing an existing script that my team uses for a google form response sheet. The script automatically creates a message body using the headers and response cells for an order every time it is submitted, roughly like this:
Type of Order: Physical
Country: America
Digital Signature:
Favorite Color:
Favorite Food: Pasta
What I've been asked to do, is have the script read through the sheet and not include the header or response for questions that are not answered in any given submission. Like so, for the previous example:
Type of Order: Physical
Country: America
Favorite Food: Pasta
I should start by saying I have close to 0 experience in javascript or Google Apps. I have tried playing around with if clauses using both the len function and a negated isblank function to no avail. These all lead to undefined errors.
As you'll see, the original script was not created by me or the people who have been using it for the last few years.
Original script
function sendFormByEmail(e)
{
Logger.log('value of e is: ' + e);
var email = "xxx#xxx.com";
var s = SpreadsheetApp.getActiveSheet();
var headers = s.getRange(1,1,1,s.getLastColumn()).getValues()[0];
var message = "";
var subject = "Type A Request: ";
// The variable e holds all the form values in an array.
// Loop through the array and append values to the body.
// Insert variables from the spreadsheet into the subject.
// In this case, I wanted the new hire's name and start date in the
// email subject. These are the 3rd and 16th columns in my form.
for(var i in headers)
message += headers[i] + ': '+ e.namedValues[headers[i]].toString() + "\n\n";
subject += e.namedValues[headers[10]].toString() + " - " +
e.namedValues[headers[12]].toString();
MailApp.sendEmail(email, subject, message, {noReply:true});
// Based off of a script originally posted by Amit Agarwal - www.labnol.org
}
You can include a check for blank values inside the for loop.
if (e.namedValues[headers[i]].toString() === "") continue;

Google Apps Script - Processing Form email as text

I have an App Script that processes a submitted Google Form. I'm capturing the email address (this is an education domain), which seems to be coming in as an object rather than a string. I'd like to convert this to a string so that I can extract the username before the # symbol.
for (var keys in columns) {
if (key =="Email address") {
studentID = e.namedValues[key];
var theEmail = studentID.replace(/#.*/, "");
}}
How can I convert studentID to a string?
Thanks for any help.

What is the procedure to email the test score of a test conducted on google forms?

I have created a test through google form, and I want to send the score result to the participants. I have created a copy of the response and put scoring through if functions. And then in the next worksheet, I have summed the score. Now I want to send that calculated score to the participants. I have entered the script in the script editor and set trigger on form submit but I am getting errors.
Would the error be because the script takes the default sheet and not the one where I have created score function? If so, how do I change that?
Here is the code that I used:
function myFunction(e)
{
var userName = e.values[1];
var userEmail = e.values[2];
var score = e.values[3];
var subject = "Thank you for your participation: Find your Score";
var message = "Thank you, " + userName + " for choosing to participate in this test. Your score is " + score;
MailApp.sendEmail(userEmail, subject, message);
}
There are two ways. Send an e-mail from the form or send a notification from the result collection spreadsheet (limited to spreadsheet collaborators).
For the first, you have to use the script editor found under tools. There are several examples to get you started. I'd recommend you take a look at: http://www.labnol.org/internet/auto-confirmation-emails/28386/
For the second, you use the notifications option, see: https://www.maketecheasier.com/send-email-notifications-google-forms/
Here is the code that I used
function myFunction(e){
var userName = e.values[1];
var userEmail = e.values[2];
var score = e.values[3];
var subject = "Thank you for your participation: Find your Score";
var message = "Thank you, " + userName + " for choosing to participate in this test. Your score is " +score;
MailApp.sendEmail (userEmail, subject, message);}