I am currently using google script to submit a google form that is then auto-populates to google doc, the document then is emailed to the recipient. I have the main structure working, but I am experiencing couple of issues, noted below:
Error 'Script function not found: atosGoogleDocForm' once the form has been submitted, I cannot understand what I am doing something wrong, but the document still get's populated and saved.
When the email has been sent, the email isn't coming from the sender of who's completed the google form, but the email is received from the email that had sent the form/created the google form (not the form filler). I don't know what I am missing here.
I would really appreciate your help.
const googleDocTemplete = DriveApp.getFileById('1-MLB3MSn0-hb11vGkRM29KEiHpAeJFybhsTGYnytSRA');
const destinationFolder = DriveApp.getFolderById('1Kdbi08wkL3gH1y8c8ghp34E8vxpaj6qQ');
const sheet = SpreadsheetApp.getActiveSpreadsheet().getSheetByName('Form responses');
const rows = sheet.getDataRange().getValues();
function atosGoogleDocForm(e) {
var timestamp = e.values[0];
var email = e.values[1];
var name = e.values[5];
var access_date = e.values[10];
var access_time = e.values[11];
var business_reason = e.values[12];
rows.forEach(function(row, index) {
if (index === 0) return;
if (row[15]) return;
const copy = googleDocTemplete.makeCopy(`${row[5]} Atos Form`, destinationFolder);
const doc = DocumentApp.openById(copy.getId());
var body = doc.getBody();
body.replaceText("{{Full Name}}", row[5]);
body.replaceText("{{Organisation}}", row[3]);
body.replaceText("{{DAS ID}}", row[4]);
body.replaceText("{{Emp Status}}", row[2]);
body.replaceText("{{Contact Address}}", row[6]);
body.replaceText("{{Contact Tel}}", row[7]);
body.replaceText("{{Atos Sponsor}}", row[8]);
body.replaceText("{{Sponsor DAS ID}}", row[9]);
body.replaceText("{{Access Date}}", access_date);
body.replaceText("{{Access Reason}}", business_reason);
body.replaceText("{{Access Time}}", access_time);
body.replaceText("{{timestamp}}", timestamp);
doc.saveAndClose();
const url = doc.getUrl();
sheet.getRange(index + 1, 16).setValue(url);
var recipient = "var5an1#hotmail.com";
var subject = name + " Atos PKI Form"
const html = '<p>Dear Reception, <br><br> Please find attached the application form for the ATOS PKI Card for ' + name + ' who will be attending to access the building on ' + access_date + ' at ' + access_time + '.' + "<br><br>Please let me know if you're experiencing any issues opening the file. The applicant will be collecting the PKI Card at Reception. <br><br>Kind regards<br><br></p>" + name + '<br><br><br>';
MailApp.sendEmail({
//from: email,
replyTo: email,
to: recipient,
cc: email,
subject: subject,
htmlBody: html,
attachments: [copy.getAs(MimeType.PDF)]
});
})
}
Related
Can you please help me, How to send dynamic mail every latest entry in google sheet?
function CustomEmail() {
var sheet = SpreadsheetApp.getActiveSheet();
var range = sheet.getRange("A2:C4");
var UserData = range.getValues();
for (i in UserData) {
var row = UserData[i];
var name = row[0];
var email = row[1];
var score = row[2];
MailApp.sendEmail(row[1], "Custom mail", "Hello " + name + ", This is an email report of your score. Your score is " + score);
}
}
Setup a trigger in your project: Trigger for "form submission". Whenever someone submits the form, script will send out the email to those whom the email wasn't sent. Also have a helper column in the sheet to update status for the script to filter out the people who already received the email, else others will keep receiving their scores everytime there's a form submission.
I'm trying to send an email with inline images to a series of users with myself in cc (myself#hotmail.com). I am trying to do this with the code written bellow. Everything seemed to work, but as soon as I added cc: 'myself#hotmail.com' it broke. My email gets send to the recipient 1x, but also to 'myself#hotmail.com' 8x. I cannot figure out what I am doing wrong, any help is much appreciated.
function sendEmails() {
SpreadsheetApp.getActiveSpreadsheet().getSheetByName("Emails").activate(); //makes sure your google sheets has the correct sheet open where you specify the emails and names
var ss = SpreadsheetApp.getActiveSpreadsheet().getActiveSheet(); //defines spreadsheet to use
var lr = ss.getLastRow(); //gets last row on which there is data
var templateText = SpreadsheetApp.getActiveSpreadsheet().getSheetByName('Template').getRange(1, 1).getValue() //gets email body from sheet 'template' which is defined in cell 1,1 -- make sure your sheet has same name else it won't work
var quotaLeft = MailApp.getRemainingDailyQuota(); //gets number of emails that you can still send
// Image URLs
var img1Url = "https://i.imgur.com/PRIVATE.png"; //CHANGE PRIVATE TAG
var img2Url = "https://i.imgur.com/PRIVATE.png"; //CHANGE PRIVATE TAG
// Fetch images as blobs, set names for attachments
var img1Blob = UrlFetchApp
.fetch(img1Url)
.getBlob()
.setName("img1Blob");
var img2Blob = UrlFetchApp
.fetch(img2Url)
.getBlob()
.setName("img2Blob");
//embeded image tags for email
var bodyImg1 = "<img src='cid:img1' style='width:1000px; height:1500px;'/>"; //specify img size here
var bodyImg2 = "<img src='cid:img2' style='width:1000px; height:1500px;'/>"; //specify img size here
if((lr-1) > quotaLeft){
Browser.msgBox("You have " + quotaLeft + " left and you're trying to send " + (lr-1) + " emails. Emails were not send"); //gives standard warning message if number of emails to be send exceeds limit
} else {
for (var i = 2; i<=lr;i++){
var currentEmail = ss.getRange(i, 1).getValue(); //gets email in excel sheet
var currentName = ss.getRange(i, 2).getValue(); //gets name in excel sheet
var subjectLine = "Invitation"; //title of email
var messageBody = templateText.replace("{name}", currentName); //replaces name in template with name of current cell, see templateText var
MailApp.sendEmail(currentEmail, subjectLine, subjectLine, {htmlBody: messageBody + bodyImg1 + bodyImg2, inlineImages:{img1: img1Blob,img2: img2Blob}, cc: 'myself#hotmail.com'});
} //close for loop
} //close else statement
} //close function
Solution:
MailApp.sendEmail({ to: currentEmail, subject: subjectLine, cc: 'myself#hotmail.com', htmlBody: messageBody + bodyImg1 + bodyImg2, inlineImages:{img1: img1Blob,img2: img2Blob}});
I am using the phonegap facebook Connect plugin to enable facebook login in my app.
However the facebook email is being returned as undefined.
Do I need to add something into my code?
I have looked up this issue on the internet and it seems my code should work. Everything else is returned except for the email address.
I would appreciate if you can help
Here is my javascript code:
facebookConnectPlugin.api('/me?fields=id, email, link, name, picture', ["public_profile"],function(data){
var fb_user_id = data.id;
var fb_email = data.email;
var fb_name = data.name;
var fb_picture_url = data.picture.data.url;
var fb_user_link = data.link;
alert("fb_email" + fb_email);
}); //end api call
Edit:
I tried a test user account with this code and the email address DID get returned. However for the real account I was testing with this doesn't work.
With more testing I tried adding in the email permission as follows however this did not work as the data that I got back stated "FACEBOOK_NON_JSON_RESULT"
facebookConnectPlugin.api('/me?fields=id, email, link, name, picture', ["public_profile", "email"],function(data){
var fb_user_id = data.id;
var fb_email = data.email;
var fb_name = data.name;
var fb_picture_url = data.picture.data.url;
var fb_user_link = data.link;
alert("fb_email" + fb_email);
}); //end api call
I find a workaround for this problem which was to do two separate api requests as follows:
facebookConnectPlugin.api('/me?fields=email', ["email"], function(apiResponse) {
//alert("api" + JSON.stringify(apiResponse));
fb_email = apiResponse.email;
alert("fb_email" +fb_email); //email being retrieved successfully
facebookConnectPlugin.api('/me?fields=id, name, link, picture', ["public_profile"],function(data) {
alert("data" + JSON.stringify(data));
var fb_user_id = data.id;
var fb_name = data.name;
var fb_picture_url = data.picture.data.url;
var fb_user_link = data.link;
alert("fb_user_id" + fb_user_id);
alert("fb_name" + fb_name);
alert("fb_picture_url" + fb_picture_url);
alert("fb_user_link" + fb_user_link);
//do stuff with facebook user data here
}
,function(error){
//api call failed
alert("api call Failed: " + JSON.stringify(error));
}); //end api
}
,function(error){
alert("email api call Failed: " + JSON.stringify(error));
}); //end api
This works perfect!
Below is where I am currently at with my code. It works just fine to attach one file. It is only attaching the last file in the folder. I want it to attach all files.
function email() {
// Get attachments folder
var attachementFolderId = values[cell][11];
Logger.log("Attachement Folder ID: " + attachementFolderId)
var getAttachementFolder = DriveApp.getFolderById(attachementFolderId).getFiles();
// Get all files from the folder
var files = DriveApp.getFolderById(attachementFolderId).getFiles();
while (files.hasNext()) {
var file = files.next();
var attachements = file.getAs(MimeType.PDF);
Logger.log(attachements)
}
MailApp.sendEmail({
to: recipient,
subject: address,
htmlBody: "Hello <br><br>" +
"Address: " + address + "<br><br>" +
"Description: " + description,
attachments: [attachements]
})
}
Your solution is not right. try like below :
var attachements = [];
while (files.hasNext()) {
var file = files.next();
attachements.push(file.getAs(MimeType.PDF));// the push method add elements to the attachements array
Logger.log(attachements)
}
And in the end :
MailApp.sendEmail({
to: recipient,
subject: address,
htmlBody: "Hello <br><br>" +
"Address: " + address + "<br><br>" +
"Description: " + description,
attachments: attachements
})
I figured it out. Probably simple mistake to experienced coders...all I did was create an array and each time it finds a file and get's it as a blob, add it to the array.
attachmentsArray[attachmentsArray.length] = attachmentFiles;
Is the code I added just below
var attachmentFiles = file.getAs(MimeType.PDF);
Then instead of
attachments: [attachements]
I put this
attachments: attachmentsArray
I have a Google form which submits to a spreadsheet. I then have written this code which sends an email with the results. Can anyone tell me how I make the email be submitted by the person who submitted the form?
function Initialize() {
var triggers = ScriptApp.getScriptTriggers();
for (var i in triggers) {
ScriptApp.deleteTrigger(triggers[i]);
}
ScriptApp.newTrigger("SendConfirmationMail")
.forSpreadsheet(SpreadsheetApp.getActiveSpreadsheet())
.onFormSubmit()
.create();
}
function SendConfirmationMail(e) {
try {
var ss, cc, subject, columns;
var message, value, textbody, sendername, sender;
// This is my email address and I will be in the CC
cc = e.namedValues["Username"].toString();
// This will show up as the sender's name
sendername = e.namedValues["Name"].toString();
subject = "Ticket Submitted";
message = "We have received your details.<br>Thanks!<br><br>";
ss = SpreadsheetApp.getActiveSheet();
columns = ss.getRange(1, 1, 1, ss.getLastColumn()).getValues()[0];
// This is the submitter's email address
sender = e.namedValues["Username"].toString();
// Only include form values that are not blank
for ( var keys in columns ) {
var key = columns[keys];
if ( e.namedValues[key] ) {
message += key + ' :: '+ e.namedValues[key] + "<br />";
}
}
textbody = message.replace("<br>", "\n");
GmailApp.sendEmail(sender, subject, textbody,
{cc: cc, name: sendername, htmlBody: message});
} catch (e) {
Logger.log(e.toString());
}
}
This is not possible, nor it should be. You want to impersonate someone else without their consent.
The archaic email system unfortunately allows that, therefore making easier the life of spammers and phishing scams. But Google and other Internet companies work hard to prevent and filter this kind of emails.
Bottom line, you will not be able to send an email as somebody else from a Google app unless it's an authorized account in your Gmail.
The best you can do is set the reply-to address.