How to send emails based on data filled in a form? - email

function ifstatement() {
const ss = SpreadsheetApp.getActiveSpreadsheet();
const ws = ss.getSheetByName("Product Form");
const ws2 = ss.getSheetByName("Email details");
var Avals = ws.getRange("c1:c").getValues();
var lr = Avals.filter(String).length;
Logger.log(lr);
var recipient = ws.getRange(lr,2).getValue();
var sub = ws.getRange(lr,4).getValue();
var mailTemp = ws.getRange(lr,5).getValue();
var impfield1 = ws.getRange(lr,6).getValue();
var impfield2 = ws.getRange(lr,8).getValue();
var impfield3 = ws.getRange(lr,10).getValue();
var fieldvalue1 = ws.getRange(lr,7).getValue();
var fieldvalue2 = ws.getRange(lr,9).getValue();
var fieldvalue3 = ws.getRange(lr,11).getValue();
var heading = ws.getRange(lr,12).getValue();
var subheading = ws.getRange(lr,13).getValue();
var body = ws.getRange(lr,14).getValue();
var footer = ws.getRange(lr,15).getValue();
var attach = ws.getRange(lr,17).getValue();
var tomail = ws.getRange(lr,16).getValue();
var file1 = attach.split(",").map(url => DriveApp.getFileById(url.trim().split("=")[1]).getBlob());
var AvalsWealth = ws2.getRange("b1:b").getValues();
var AvalsInsurance = ws2.getRange("c1:c").getValues();
var AvalsTeam = ws2.getRange("e1:e").getValues();
var lrWealth = AvalsWealth.filter(String).length;
var lrInsurance = AvalsInsurance.filter(String).length;
var lrTeam = AvalsTeam.filter(String).length;
Logger.log(mailTemp);
Logger.log(heading);
if(tomail=="Wealth RMs"){
var bccmail = ws2.getRange(2,2,lrWealth).getValues().toString();
} else if(tomail=="Self"){
var bccmail = recipient;
} else if(tomail=="Insurance RMs"){
var bccmail = ws2.getRange(2,3,lrInsurance).getValues().toString();
} else if(tomail=="All India"){
var bccmail = ws2.getRange(2,4,lrTeam).getValues().toString();
}
Logger.log(bccmail)
if(mailTemp=="HTML1"){
const htmlTemplate = HtmlService.createTemplateFromFile("HTML1");
htmlTemplate.heading = heading;
htmlTemplate.subheading = subheading;
htmlTemplate.body = body;
htmlTemplate.footer = footer;
htmlTemplate.impfield1 = impfield1;
htmlTemplate.impfield2 = impfield2;
htmlTemplate.impfield3 = impfield3;
htmlTemplate.fieldvalue1 = fieldvalue1;
htmlTemplate.fieldvalue2 = fieldvalue2;
htmlTemplate.fieldvalue3 = fieldvalue3;
const htmlforemail = htmlTemplate.evaluate().getContent();
GmailApp.sendEmail('',
""+ sub + "",
'',
{htmlBody: htmlforemail,
bcc: bccmail,
attachments: file1}
) } else if(mailTemp=="HTML2"){
const htmlTemplate = HtmlService.createTemplateFromFile("HTML2");
htmlTemplate.heading = heading;
htmlTemplate.subheading = subheading;
htmlTemplate.body = body;
htmlTemplate.footer = footer;
htmlTemplate.impfield1 = impfield1;
htmlTemplate.impfield2 = impfield2;
htmlTemplate.impfield3 = impfield3;
htmlTemplate.fieldvalue1 = fieldvalue1;
htmlTemplate.fieldvalue2 = fieldvalue2;
htmlTemplate.fieldvalue3 = fieldvalue3;
const htmlforemail = htmlTemplate.evaluate().getContent();
GmailApp.sendEmail('',
""+ sub + "",
'',
{htmlBody: htmlforemail,
bcc: bccmail,
attachments: file1}
) } else if(mailTemp=="HTML3"){
const htmlTemplate = HtmlService.createTemplateFromFile("AUM Annual awards");
htmlTemplate.heading = heading;
htmlTemplate.subheading = subheading;
htmlTemplate.body = body;
htmlTemplate.footer = footer;
htmlTemplate.impfield1 = impfield1;
htmlTemplate.impfield2 = impfield2;
htmlTemplate.impfield3 = impfield3;
htmlTemplate.fieldvalue1 = fieldvalue1;
htmlTemplate.fieldvalue2 = fieldvalue2;
htmlTemplate.fieldvalue3 = fieldvalue3;
const htmlforemail = htmlTemplate.evaluate().getContent();
GmailApp.sendEmail('',
""+ sub + "",
'',
{htmlBody: htmlforemail,
bcc: bccmail}
) } else if(mailTemp=="HTML4"){
const htmlTemplate = HtmlService.createTemplateFromFile("HTML4");
htmlTemplate.heading = heading;
htmlTemplate.subheading = subheading;
htmlTemplate.body = body;
htmlTemplate.footer = footer;
htmlTemplate.impfield1 = impfield1;
htmlTemplate.impfield2 = impfield2;
htmlTemplate.impfield3 = impfield3;
htmlTemplate.fieldvalue1 = fieldvalue1;
htmlTemplate.fieldvalue2 = fieldvalue2;
htmlTemplate.fieldvalue3 = fieldvalue3;
const htmlforemail = htmlTemplate.evaluate().getContent();
GmailApp.sendEmail('mayank.agarwal#aumcap.com',
""+ sub + "",
'',
{htmlBody: htmlforemail,
bcc: bccmail,
attachments: file1}
) }
}
I have this small setup where I have a Google Sheet, Google Appscript and Google form.
The user needs to input data in a Google Form - and once the sheet (linked with Form response) receives the updated row - a script is triggered which takes the data from the row and feeds it into the sheet and sends mail to the selected set of users.
Now the problem I am facing is that I need to send this mail to approx 100-150 people, however Googel appscript does not allow me to send mail to more than 30 participants at a time.
I understand that I need an Email service for this, however, I am unable to find any good solution wherein I can store my templates and the user just fills up data fields and shoots the mail.
Maybe because I am very new to this tech field so thats why.
Can anyone please guide me as to what is the setup I need to use for my purpose?
Thanks!

The first thing you need to do is to keep the BCC list as an array until it's necessary. This will allow us to make chunks out of it. This means removing the .toString() at the end of assigning bccmail.
Then, we need a custom function to send the email in batches of emails. I'm calling that function sendMassEmail.
function sendMassEmail(bccList, subject, plainBody, htmlBody, attachments) {
for (let bcc of chunks(bccList, 30)) {
GmailApp.sendEmail(
'',
subject,
plainBody,
{
htmlBody,
bcc: bcc.join(','),
attachments,
},
)
}
}
Chunks is a function that does exactly that, gets the elements of an array in chunks. My favorite implementation for this case is by using a generator.
I've kept the plain text body as it's important to generate it if you are sending it, as it is shown in most clients on the Inbox. Also, some of them can only read this ones (think smart watch).
The last argument (attachments) is optional.
Here is an example on how you would use it:
sendMassEmail(
bccmail,
sub.toString(),
'', // Should probably change it
htmlforemail,
file1,
)
Note that it's better to use toString() than concatenating into an empty string.
References
GmailApp.sendEmail(recipient, subject, body, options) (Apps Script reference)
for..of (MDN JavaScript reference)
Functions (MDN JavaScript guide)
Split array into chunks (StackOverflow question)

Related

I'm having problem binding data to content control using ooxml and office.js

I'm developing a word addin that pulls xml data from our servers and binds it to a rich text content control. The user should only be able to format the data within the content control but can't edit or delete the data.
This is the code i've been able to come up with but it's not working..
var ooxmlPackage = new DOMParser().parseFromString(
'<pkg:package xmlns:pkg="http://schemas.microsoft.com/office/2006/xmlPackage"></pkg:package>',
"text/xml"
);
var ooxmlPart = ooxmlPackage.createElement("pkg:part");
ooxmlPart.setAttribute("pkg:name", "/_rels/.rels");
ooxmlPart.setAttribute("pkg:contentType", "application/vnd.openxmlformats-package.relationships+xml");
ooxmlPart.setAttribute("pkg:padding", "512");
var ooxmlxmlData = ooxmlPackage.createElement("pkg:xmlData");
var ooxmlRelationships = ooxmlPackage.createElement("Relationships");
ooxmlRelationships.setAttribute("xmlns", "http://schemas.openxmlformats.org/package/2006/relationships");
var ooxmlRelationship = ooxmlPackage.createElement("Relationship");
ooxmlRelationship.setAttribute("Id", "rId1"); //TODO: generate unique ID
ooxmlRelationship.setAttribute(
"Type",
"http://schemas.openxmlformats.org/officeDocument/2006/relationships/officeDocument"
);
ooxmlRelationship.setAttribute("Target", "word/document.xml");
ooxmlRelationships.appendChild(ooxmlRelationship);
ooxmlxmlData.appendChild(ooxmlRelationships);
ooxmlPart.appendChild(ooxmlxmlData);
var ooxmlDocPart = ooxmlPackage.createElement("pkg:part");
ooxmlDocPart.setAttribute("pkg:name", "/word/document.xml");
ooxmlDocPart.setAttribute(
"pkg:contentType",
"application/vnd.openxmlformats-officedocument.wordprocessingml.document.main+xml"
);
var ooxmlDocPartxmlData = ooxmlPackage.createElement("pkg:xmlData");
var ooxmlDocument = ooxmlPackage.createElement("w:document");
ooxmlDocument.setAttribute("xmlns:w", "http://schemas.openxmlformats.org/wordprocessingml/2006/main");
ooxmlDocument.setAttribute("xmlns:w15", "http://schemas.microsoft.com/office/word/2012/wordml");
var ooxmlDocumentBody = ooxmlPackage.createElement("w:body");
var ooxmlDocumentParagraph1 = ooxmlPackage.createElement("w:p");
var ooxmlContentControl = ooxmlPackage.createElement("w:sdt");
var sdtPr = ooxmlPackage.createElement("w:sdtPr");
//var lk = ooxmlPackage.createElement("w:lock");
//lk.setAttribute("w:val", "sdtContentLocked");
//sdtPr.appendChild(lk);
var alias = ooxmlPackage.createElement("w:alias");
alias.setAttribute("w:val", "MyControl");
sdtPr.appendChild(alias);
var id1 = ooxmlPackage.createElement("w:id");
id1.setAttribute("w:val", "1382295294");
sdtPr.appendChild(id1);
//var appr = ooxmlPackage.createElement("w15:appearance");
//appr.setAttribute("w15:val", "hidden");
//sdtPr.appendChild(appr);
sdtPr.appendChild(ooxmlPackage.createElement("w:showingPlcHdr"));
//var plchdlr = ooxmlPackage.createElement("w:placeholder");
//var docPrt = ooxmlPackage.createElement("docPart");
//docPrt.setAttribute("w:val", "defaultPlaceHolder_-1854013440");
//plchdlr.appendChild(docPrt);
//sdtPr.appendChild(plchdlr);
var bindingNode = ooxmlPackage.createElement("w15:dataBinding");
//bindingNode.setAttribute("w:prefixMappings","xmlns:ns0='custom'");
bindingNode.setAttribute("w:xpath","/Root[1]/Node[1]");
bindingNode.setAttribute("w:storeItemID", "{C2F77B86-6131-4922-803B-54FACB654C16}");
sdtPr.appendChild(bindingNode);
ooxmlContentControl.appendChild(sdtPr);
var sdtContent = ooxmlPackage.createElement("w:sdtContent");
var parag = ooxmlPackage.createElement("w:p");
var r = ooxmlPackage.createElement("w:r")
var t = ooxmlPackage.createElement("w:t")
//t.innerHTML= '[This is a test]';
r.appendChild(t);
parag.appendChild(r);
sdtContent.appendChild(parag);
ooxmlContentControl.appendChild(sdtContent);
ooxmlDocumentBody.appendChild(ooxmlDocumentParagraph1);
ooxmlDocumentBody.appendChild(ooxmlContentControl);
ooxmlDocument.appendChild(ooxmlDocumentBody);
ooxmlDocPartxmlData.appendChild(ooxmlDocument);
ooxmlDocPart.appendChild(ooxmlDocPartxmlData);
ooxmlPackage.documentElement.appendChild(ooxmlPart);
ooxmlPackage.documentElement.appendChild(ooxmlDocPart);
var serializer = new XMLSerializer();
var ooxmlPackageString = serializer.serializeToString(ooxmlPackage);
console.log(ooxmlPackageString);
Office.context.document.setSelectedDataAsync(ooxmlPackageString, { coercionType: "ooxml" });
Office.context.document.customXmlParts.getByIdAsync(
'<Root xmlns=""> <Node>VALUE1</Node></root>',
function (result) { });
It just inserts an empty content control when it runs, it doesn't map the xml node data as expected.

Unable to add inline image to email in google apps script

I'm new to Google Apps script and am trying to add an image inline to an automated response email.
The auto reply works perfectly, the main text of the email formats well in plain text and html.
the problem i'm facing is that the image does not appear.
my code:
// This constant is written in column Y for rows for which an email
// has been sent successfully.
var EMAIL_SENT = 'EMAIL_SENT';
/**
* Sends non-duplicate emails with data from the current spreadsheet.
*/
function sendEmails2() {
var sheet = SpreadsheetApp.getActiveSpreadsheet();
SpreadsheetApp.setActiveSheet(sheet.getSheetByName('Data'))
var startRow = 2; // First row of data to process
// Fetch the range
var dataRange = sheet.getRange("L2:L1000")
var dataRange2 = sheet.getRange("K2:K1000")
var dataRange3 = sheet.getRange("O2:O1000")
var dataRange4 = sheet.getRange("Y2:Y1000")
var dataRange5 = sheet.getRange("B2:B1000")
// Fetch values for each row in the Range.
var data = dataRange.getValues();
var data2 = dataRange2.getValues();
var data3 = dataRange3.getValues();
var data4 = dataRange4.getValues();
var data5 = dataRange5.getValues();
for (var i = 0; i < data.length; ++i) {
var yesno = data2[i]
if(yesno == "Yes"){
var TFlogoUrl = "https://drive.google.com/openid=1nzmvP_zzOms1HiBoFCsVLFjDM6ZzM287";
var TFlogoBlob = UrlFetchApp
.fetch(TFlogoUrl)
.getBlob()
.setName("TFlogoBlob");
var emailAddress = data[i];
var ShipID = data3[i];
var cmdrID = data5[i];
var TFmsg = "Hi " + cmdrID + ",/n /nThank you for signing up to The Fatherhoods Lost Souls Expedition./n /nYour unique Ship ID is: " + ShipID + "/n /nWe look forward to seeing you on the expedition CMDR!/n /nFly Safe,/nThe Lost Souls Expedition team.";
var htmlTFmsg = "Hi " + cmdrID + ",<br> <br>Thank you for signing up to The Fatherhoods Lost Souls Expedition.<br> <br>Your unique Ship ID is: " + ShipID + "<br> <br>We look forward to seeing you on the expedition CMDR!<br> <br>Fly Safe,<br>The Lost Souls Expedition team.<br><img src='cid:TFlogo'>";
emailSent = data4[i]; // email sent (column Y)
if (emailSent != EMAIL_SENT) { // Prevents sending duplicates
var subject = "Lost Souls Expedition Sign up confirmation";
MailApp.sendEmail(emailAddress,subject,TFmsg,{
htmlBody: htmlTFmsg,
inlineImage:
{
TFlogo:TFlogoBlob
}
});
sheet.getRange("Y" + (startRow + i)).setValue(EMAIL_SENT);
// Make sure the cell is updated right away in case the script is interrupted
SpreadsheetApp.flush();
}
}
}
}
How about this modification?
Modification points:
You cannot retrieve the file blob from this URL var TFlogoUrl = "https://drive.google.com/openid=1nzmvP_zzOms1HiBoFCsVLFjDM6ZzM287";. If you want to retrieve the file blob from URL, please use var TFlogoUrl = "http://drive.google.com/uc?export=view&id=1nzmvP_zzOms1HiBoFCsVLFjDM6ZzM287";. 1nzmvP_zzOms1HiBoFCsVLFjDM6ZzM287 is the file ID.
As an another method, from the file ID, it is found that the values of getSharingAccess() and getSharingPermission() are ANYONE_WITH_LINK and VIEW, respectively. So you can also retrieve the blob using var TFlogoBlob = DriveApp.getFileById("1nzmvP_zzOms1HiBoFCsVLFjDM6ZzM287").getBlob().setName("TFlogoBlob");. I recommend this.
When you want to use the inline image to email, please modify from inlineImage to inlineImages.
The script which reflected above points is as follows.
Modified script:
Please modify your script as follows.
From:
var TFlogoUrl = "https://drive.google.com/openid=1nzmvP_zzOms1HiBoFCsVLFjDM6ZzM287";
var TFlogoBlob = UrlFetchApp.fetch(TFlogoUrl).getBlob().setName("TFlogoBlob");
To:
var id = "1nzmvP_zzOms1HiBoFCsVLFjDM6ZzM287";
var TFlogoBlob = DriveApp.getFileById(id).getBlob().setName("TFlogoBlob");
And
From:
inlineImage: {TFlogo:TFlogoBlob}
To:
inlineImages: {TFlogo:TFlogoBlob}
References:
sendEmail(recipient, subject, body, options)
If I misunderstand your question, please tell me. I would like to modify it.

Tags are appearing in left of the document in embedded Signing using template

``code` DocuSignTK.Recipient recipient = new DocuSignTK.Recipient();
recipient.Email = signer_email; // This person will use embedded signing. If you have his
// email, supply it. If you don't, use a fake email that includes your
// ClientUserID. Eg embedded_signer_{ClientUserID}#your_company.com
recipient.UserName = signer_name;
recipient.ID = 1;
recipient.Type_x = 'Signer';
recipient.RoutingOrder = 1;
recipient.RoleName = 'Signer1';
// We want this signer to be "captive" so we can use embedded signing with him
recipient.CaptiveInfo = new DocuSignTK.RecipientCaptiveInfo();
recipient.CaptiveInfo.ClientUserID = signer_user_id; // Must uniquely identify the
// Create the recipient information
DocuSignTK.ArrayOfRecipient1 recipients = new DocuSignTK.ArrayOfRecipient1();
recipients.Recipient = new DocuSignTK.Recipient[1];
recipients.Recipient[0] = recipient;
DocuSignTK.ArrayOfTemplateReferenceRoleAssignment Roles = new DocuSignTK.ArrayOfTemplateReferenceRoleAssignment();
Roles.RoleAssignment = new DocuSignTK.TemplateReferenceRoleAssignment[1];
DocuSignTK.TemplateReferenceRoleAssignment role = new DocuSignTK.TemplateReferenceRoleAssignment();
role.RoleName = 'Signer1';
role.RecipientID = 1;
Roles.RoleAssignment[0] = role;
// Create the template reference from a server-side template ID
DocuSignTK.TemplateReference templateReference = new DocuSignTK.TemplateReference();
templateReference.Template = 'd0d80082-612b-4a04-b2a1-0672eb720491';
templateReference.TemplateLocation = 'Server';
templateReference.RoleAssignments = Roles;
// Construct the envelope information
DocuSignTK.EnvelopeInformation envelopeInfo = new DocuSignTK.EnvelopeInformation();
envelopeInfo.AccountId = account_Id;
envelopeInfo.Subject = 'Subject';
envelopeInfo.EmailBlurb = 'Email content';
// Make the call
try {
//DocuSignTK.EnvelopeStatus result = api_sender.CreateAndSendEnvelope(envelope);
// Create draft with all the template information
DocuSignTK.ArrayOfTemplateReference TemplateReferenceArray = new DocuSignTK.ArrayOfTemplateReference();
TemplateReferenceArray.TemplateReference = new DocuSignTK.TemplateReference[1];
TemplateReferenceArray.TemplateReference[0] = templateReference;
DocuSignTK.EnvelopeStatus result = api_sender.CreateEnvelopeFromTemplates( TemplateReferenceArray, recipients, envelopeInfo, true);
envelope_id = result.EnvelopeID;
System.debug('Returned successfully, envelope_id = ' + envelope_id );
} catch ( CalloutException e) {
System.debug('Exception - ' + e );
error_code = 'Problem: ' + e;
error_message = error_code;
} `code``
I am integrating Docusign for embedded signing. I am using SOAP API and used method CreateEnvelopeFromTemplates . Template I created is having some fields/Tabs. But once I open signing url these fields are located on side of the document instead of the location which I sent in template.
I have also assigned Role name for recipient but it is not working. Please help.
Click here to see screenshot
Here is the C# code to create an envelope from template using the DocuSign SOAP Api. Documentation here
string apiUrl = "https://demo.docusign.net/api/3.0/api.asmx";
string accountId = "Enter accountId"; //
string email = "Enter email";
string userName = "Enter intergrator key";
userName += email;
string _password = "Enter password";
var apiClient = new DocuSignTK.APIServiceSoapClient("APIServiceSoap", apiUrl);
apiClient.ClientCredentials.UserName.UserName = userName;
apiClient.ClientCredentials.UserName.Password = _password;
// Construct all the recipient information
var recipients = new DocuSignTK.Recipient[1];
recipients[0] = new DocuSignTK.Recipient();
recipients[0].Email = "recipientone#acme.com";
recipients[0].UserName = "recipient one";
recipients[0].Type = DocuSignTK.RecipientTypeCode.Signer;
recipients[0].ID = "1";
recipients[0].RoutingOrder = 1;
recipients[0].RoleName = "Signer1";
var roles = new DocuSignTK.TemplateReferenceRoleAssignment[1];
roles[0] = new DocuSignTK.TemplateReferenceRoleAssignment();
roles[0].RoleName = recipients[0].RoleName;
roles[0].RecipientID = recipients[0].ID;
// Use a server-side template -- you could make more than one of these
var templateReference = new DocuSignTK.TemplateReference();
templateReference.TemplateLocation = DocuSignTK.TemplateLocationCode.Server;
// TODO: replace with template ID from your account
templateReference.Template = "d0d80082-612b-4a04-b2a1-0672eb720491";
templateReference.RoleAssignments = roles;
// Construct the envelope information
DocuSignTK.EnvelopeInformation envelopeInfo = new DocuSignTK.EnvelopeInformation();
envelopeInfo.AccountId = " ";
envelopeInfo.Subject = "create envelope from templates test";
envelopeInfo.EmailBlurb = "testing docusign creation services";
// Create draft with all the template information
DocuSignTK.EnvelopeStatus status = apiClient.CreateEnvelopeFromTemplates(new DocuSignTK.TemplateReference[] { templateReference },
recipients, envelopeInfo, false);
I downloaded a template from production and uploaded in sandbox but once I recreated similar template in Sandbox only and used it's template ID in code then it is working perfectly. Apparently, There seems to be some issue with import template utility of Docusign.

Extract unread emails (in Plain Text) and store in a Google Doc

Problem: Daily we get a dozen of mails. We need to print all of them in regular basis. Is it possible for a Google Apps Script to read only the unread mails and to store them in a Google Doc? No HTML nothing, I just need the plain text in the following format.
​From: S. Banerjee Date: 3 January
2017 at 02:40 Subject: Re: Happy New Year To: "Br. Sayan"
...... ...... Message ..... ......
I was searching for a solution, but only managed to get something like the following here. Now we need to get the msgIDs of the unread mail pass them on to the function. Rest of the formatting can be solved later on piecemeal basis I think.
function saveGmail(msgID) {
// Based on Drive Scoop
// Available at https://github.com/google/gfw-deployments
var message = GmailApp.getMessageById(msgID);
// Grab the message's headers.
var from = message.getFrom();
var subject = message.getSubject();
var to = message.getTo();
var cc = message.getCc();
var date = message.getDate();
var body = message.getBody();
// Begin creating a doc.
var document = DocumentApp.create(subject);
var document_title = document.appendParagraph(subject);
document_title.setHeading(DocumentApp.ParagraphHeading.HEADING1);
var style = {};
style[DocumentApp.Attribute.HORIZONTAL_ALIGNMENT] = (DocumentApp.HorizontalAlignment.CENTER);
document_title.setAttributes(style);
var headers_heading = (document.appendParagraph("Gmail Message Headers"));
headers_heading.setHeading(DocumentApp.ParagraphHeading.HEADING2);
AddGmailHeaderToDoc(document, "From", from);
AddGmailHeaderToDoc(document, "To", to);
AddGmailHeaderToDoc(document, "Cc", cc);
AddGmailHeaderToDoc(document, "Date", date);
AddGmailHeaderToDoc(document, "Subject", subject);
var body_heading = (
document.appendParagraph("Body (without Markup)"));
body_heading.setHeading(DocumentApp.ParagraphHeading.HEADING2);
var sanitized_body = body.replace(/<\/div>/, "\r\r");
sanitized_body = sanitized_body.replace(/<br.*?>/g, "\r");
sanitized_body = sanitized_body.replace(/<\/p>/g, "\r\r");
sanitized_body = sanitized_body.replace(/<.*?>/g, "");
sanitized_body = sanitized_body.replace(/'/g, "'");
sanitized_body = sanitized_body.replace(/"/g, '"');
sanitized_body = sanitized_body.replace(/&/g, "&");
sanitized_body = sanitized_body.replace(/\r\r\r/g, "\r\r");
var paragraph = document.appendParagraph(sanitized_body);
document.saveAndClose();
return document.getUrl();
}
function AddGmailHeaderToDoc(document, header_name, header_value) {
if (header_value === "") return;
var paragraph = document.appendParagraph("");
paragraph.setIndentStart(72.0);
paragraph.setIndentFirstLine(36.0);
paragraph.setSpacingBefore(0.0);
paragraph.setSpacingAfter(0.0);
var name = paragraph.appendText(header_name + ": ");
name.setBold(false);
var value = paragraph.appendText(header_value);
value.setBold(true);
}
Your help will be very much appreciated!!
An easier way might be to use 'is:unread' search
var threads = GmailApp.search('is:unread');
var messages = threads[0].getMessages();
for (var i = 0; i < messages.length; i++) {
Logger.log(messages[i].getId());
}
This will log the Id's but you can return them as well. Also note that threads and messages are different. The above will get the first unread thread and all the messages in this thread (even if the messages are read).

Google Form. Confirmation Email Script. With edit url

I have two working trigger functions in Google Script that fire when a form response spreadsheet gets a new submission. One inserts the "edit your submission" url into the spreadsheet. The other looks up the response's email and sends them a confirmation.
What I'm having a hard time understanding is how to populate the url first, and then send an email containing that url.
(Google Script is different to debug than js in the browser :\ )
Setup triggers
function Initialize() {
var triggers = ScriptApp.getScriptTriggers();
for (var i in triggers) {
ScriptApp.deleteTrigger(triggers[i]);
}
ScriptApp.newTrigger("SendConfirmationMail")
.forSpreadsheet(SpreadsheetApp.getActiveSpreadsheet())
.onFormSubmit()
.create();
assignEditUrls();
}
On form submit, searches for column titled "Clients Email", and sends a formatted email to them.
function SendConfirmationMail(e) {
try {
var ss, cc, sendername, subject, columns;
var message, value, textbody, sender;
var url;
// This is your email address and you will be in the CC
cc = Session.getActiveUser().getEmail();
// This will show up as the sender's name
sendername = "XXXX";
// Optional but change the following variable
// to have a custom subject for Google Docs emails
subject = "Form Complete: Mobile App - Client Questionnaire";
// This is the body of the auto-reply
message = "Confirmation text here.<br><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["Clients Email"].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\n");
GmailApp.sendEmail(sender, subject, textbody,
{cc: cc, name: sendername, htmlBody: message});
} catch (e) {
Logger.log(e.toString());
}
}
Separate function. Looks up form and applies the edit URL to the 26th column.
function assignEditUrls() {
var form = FormApp.openById('10BVYipGhDa_AthabHE-xxxxxx-hg');
//enter form ID here
var sheet = SpreadsheetApp.getActiveSpreadsheet().getSheetByName('Form Responses');
//Change the sheet name as appropriate
var data = sheet.getDataRange().getValues();
var urlCol = 26; // column number where URL's should be populated; A = 1, B = 2 etc
var responses = form.getResponses();
var timestamps = [], urls = [], resultUrls = [];
for (var i = 0; i < responses.length; i++) {
timestamps.push(responses[i].getTimestamp().setMilliseconds(0));
urls.push(responses[i].getEditResponseUrl());
}
for (var j = 1; j < data.length; j++) {
resultUrls.push([data[j][0]?urls[timestamps.indexOf(data[j][0].setMilliseconds(0))]:'']);
}
sheet.getRange(2, urlCol, resultUrls.length).setValues(resultUrls);
}
Programmers are provided no direct control over the order that trigger functions will be invoked, when they are dependent on the same event.
In your situation though, there are a couple of options available.
Use only one trigger function for the event, and have it invoke the current functions in the order you require. (Alternatively, set assignEditUrls() up as the only trigger function, and have it call SendConfirmationMail() after completing its task.
Have SendConfirmationMail() check for the availability of the Edit URL, and call Utilities.sleep() if the URL isn't ready yet. (In a loop, until ready.)