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.
Related
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
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;
I am trying to compare an email address inputed from a form to what is already in the database and I figure the best way to do so is with using a findByEmail method.
I expected that to find the email address for a specific entry in the table but instead it returns the whole entry (first name, last name, and more…).
How do I only find the email address of the entry in the table?
I know I can use a foreach to iterate through the entry but I think that kinda defeats the purpose of using a findByEmail function.
Here’s what I’ve tried so far:
$formEmail = $form->get('email')->getData();
$personEmail = $em->getRepository('UserBundle:User')->findByEmail($formEmail); //Should just find the email address of a person in the database.
var_dump($personsEmail); //returns the whole row associated with the email address (first name, last name…..)
var_dump(if($formEmail == $personEmail));die; //returns false when it should be true because it finds the whole row instead of the email address
If you fetched the entity successfully by email then the email must match.
$formEmail = $form->get('email')->getData();
$person = $em->getRepository('UserBundle:User')->findOneByEmail($formEmail);
if ($person instanceof User) {
// you found a user by email, so the email therefore must match ...
}
Note, use findOneBy not findBy, then you will fetch the object directly instead of in a collection.
Alternatively if you must fetch just the email address for comparison.
$email = $em->createQueryBuilder()
->select('u.email')
->from('UserBundle:User', 'u')
->where('u.email = :email')
->setParameter('email', $formEmail)
->getQuery()
->getSingleScalarResult()
;
Note though that you could just use $person->getEmail() in my first example for the same result.
I have a google spreadsheet which contains multiple sheets (or tabs) within it. Each sheet is populated from its own unique form. None of the forms are embedded in the spreadsheet.
Periodically, I need to delete all the data in the sheets, and also delete all the old responses which are saved in each of the forms. I can do this using a .gs script which resides in the spreadsheet. It accesses the form by its ID (the long string which appears in its URI). This requires the ID string to be hardcoded in my .gs script.
Ideally, I would like to access each form from the sheet object (i.e. the destination for each forms entries). Mock up code would look like this...
var ss = SpreadSheedApp.getActiveSpreadsheet();
var sheet = ss.getActiveSheet();
var form = sheet.getMyAssociatedSourceForm(); // my dream method :-)
form.deleteAllResponses() // this method already exists
Does anyone know if this is possible? Or will I have to continue to use the ID (which is currently working)?
rgds...
I think you can do this without literally typing in ID's into your script. But, you would need to get every Form in your drive, loop through them all and get the destinationId() of every Form.
Google Documentation
Then compare the destinationId with the current spreadsheets ID, which you can get without needing to "hard code" it:
function deleteAllResponses() {
var thisSS_ID = SpreadsheetApp.getActiveSpreadsheet().getId();
var allForms = DriveApp.getFilesByType(MimeType.GOOGLE_FORMS);
var thisFormFile, thisFormFileID = "", thisForm, theDestID = "";
while (allForms.hasNext()) {
thisFormFile = allForms.next();
thisFormFileID = thisFormFile.getId();
thisForm = FormApp.openById(thisFormFileID);
try {
theDestID = thisForm.getDestinationId();
} catch(err) {
continue;
};
if (theDestID === "" || theDestID === undefined) {
continue;
};
if (theDestID === thisFormFileID) {
thisForm.deleteAllResponses();
};
};
};
I have not tested this, so don't know if it works. If it does, let me know in the comments section.
I have a script behind a Google spreadsheet that sends an email once certain cells of a row is completed. The script works by sending to multiple hard coded email addresses. How can I add the current user's email address as a 2nd CC? One of the CC is hard coded but the 2nd changes depending on the person updating the spreadsheet. I know how to grab the email address but how do I pass it as a variable so it actually gets CC-ed?
var currentemail = Session.getActiveUser().getEmail();
var options = {cc: 'Session.getActiveUser().getEmail(), someotheremail#domain.com'};
or
var options = {cc: 'currentemail, someotheremail#domain.com'};
GmailApp.sendEmail(email, subject, body, options);
Obviously these do not work :)
Many thanks in advance
this can be done like below :
function sendWithCc(){
var currentemail = Session.getActiveUser().getEmail();
var options = {};// create object
options['cc'] = currentemail+',someotheremail#domain.com';// add key & values (comma separated in a string)
GmailApp.sendEmail('somemail#domain.com', 'subject', 'body', options);
// I stringified 'subject' and 'body' to make that test work without defining values for it
}
Your examples should be modified as follows:
var options = {cc: Session.getActiveUser().getEmail()+', someotheremail#domain.com'};
Or
var options = {cc: currentemail+', someotheremail#domain.com'};
You cannot call a function, or reference a variable, from within a string. Instead, use the + operator to join the value of your variable (or the return value of your function call) with the string.
Note, depending on the context in which this code will be used, the script may not have permission to access the users identity regardless. See the notes under GetActiveUser() here: https://developers.google.com/apps-script/reference/base/session#getActiveUser()