Sheets to Docs to Email - google-apps-script

I have created a spreadsheet that contains quite a large amount of data.
The plan is to consolidate this data into a readable email to be sent out weekly, each specific row of data is its own email.
I tried going directly from sheets to email, but frankly it never quite looked right, plus the idea was to have a document template, where we could easily update the body without messing with code.
So I decided to write a email template in DOCS, set out a table, then have a script that copied the email template and updated the table with the row of data the script was looking at, then send it via email.
The code works great, but there is one little snag, the table never quite copies over to the email properly.
Below is are images of how the table is formatted in the email compared to the format in the template.
I just can not figure out how or why the format does not carry over.
I have also listed my code below, any help or advice on how I achieve the correct formatting would be appreciated.
UPDATE;
I have updated the question to show the code where we find the url of the document and convert to HTML,
var classArray=[];
//get html from Doc
var subject= row[30];
var forDriveScope = DriveApp.getStorageUsed(); //needed to get Drive Scope requested
var url = "https://docs.google.com/feeds/download/documents/export/Export?id="+newID+"&exportFormat=html";
var param = {
method : "get",
headers : {"Authorization": "Bearer " + ScriptApp.getOAuthToken()},
muteHttpExceptions:true,
};
var html = UrlFetchApp.fetch(url,param).getContentText();
//docs uses css in the head, but gmail only takes it inline. need to move css inline.
//DOES NOT HANDLE HEADER CLASSES (eg h1, h2).
var headEnd = html.indexOf("</head>");
//get everything between <head> and </head>, remove quotes
var head = html.substring(html.indexOf("<head>")+6,headEnd).replace(/"/g,"");
//split on .c# with any positive integer amount of #s
var regex = /\.c\d{1,}/;
var classes = head.split(regex);
//get class info and put in an array index by class num. EG c4{size:small} will put "size:small" in classArray[4]
var totalLength = 0;
for(var i = 1; i < classes.length; i++){
//assume the first string (classes[0]) isn't a class definition
totalLength = totalLength + classes[i-1].length;
var cNum = head.substring(totalLength+2,head.indexOf("{",totalLength)); //totallength+2 chops off .c, so get what's between .c and {
totalLength = totalLength + 2 + cNum.length //add .c and the number of digits in the num
classArray[cNum] = classes[i].substring(1,classes[i].indexOf("}")); //put what's between .c#{ and } in classArray[#]
}
//now we have the class definitions, let's put it in the html
html = html.substring(headEnd+7,html.indexOf("</html>")); //get everything between <html> and </html>
var classMatch = /class=\"(c\d{1,} ){0,}(c\d{1,})\"/g
//matches class="c# c#..." where c#[space] occurs any number of times, even zero times, and c#[no space] occurs after it, exactly once
html = html.replace(classMatch,replacer); //replace class="c# c#..." with the definitions in classArray[#]
//make the e-mail!
GmailApp.sendEmail(row[31], subject, "HTML is not enabled in your email client. Sad face!", {
htmlBody: html,
});
function replacer(match){
var csOnly = match.substring(7,match.length-1); //class=" has 7 chars, remove the last "
var cs = csOnly.split(" "); //get each c#
var ret = "style=\""
for(var cCount = 0; cCount < cs.length; cCount++){
ret = ret + classArray[cs[cCount].substring(1)];
}
return ret+"\"";
}
})
}

The comments in the code says that Gmail can only use inline styling. That was true several years ago but currently Gmail allows to have a style tag inside a head tag. Considering this, the script could be much more simple that the one included in the question.
Below there is a script showing a sample that sends a Google Document content as the HTML body of an email message.
/**
* Get document as HTML
* Adapted from https://stackoverflow.com/a/28503601/1595451
*/
function getGoogleDocumentAsHTML(id) {
var forDriveScope = DriveApp.getStorageUsed(); //needed to get Drive Scope requested
var url = "https://docs.google.com/feeds/download/documents/export/Export?id=" + id + "&exportFormat=html";
var param = {
method: "get",
headers: { "Authorization": "Bearer " + ScriptApp.getOAuthToken() },
muteHttpExceptions: true,
};
var html = UrlFetchApp.fetch(url, param).getContentText();
return html;
}
/**
* Send the content of a Google Document as the HTML body of a email message
*/
function sendEmail(){
const url = /* add here the URL of your Google Document */;
const id = url.match(/[^\/]{44}/)[0];
const doc = getGoogleDocumentAsHTML(id);
const head = doc
.replace(/<meta[^>]+?>/g,'') // get rid of the meta tags
.match(/<head.+?<\/head>/)[0];
const body = doc.match(/<body[^>]+?>.+<\/body>/)[0];
const htmlBody = [head,body].join('\n');
MailApp.sendEmail({
to: /*add here the recipient email address */,
subject: /*add here the email subject */,
htmlBody: htmlBody
})
}
NOTE: You might want to clear the class of the body tag to avoid the margins set for it.

Related

Extract Inline images from Gmail Body

I am trying to extract all the images store in Inline body of email, store it in drive folder.
I am tryin to use this code
function GETGMEmails(){
var label = GmailApp.getUserLabelByName ('WHOLESALE REP');
var threads = label.getThreads();
for(var i = threads.length - 1; i >= 0; i--){
var messages = threads[i].getMessages();
for (var j = 0; j < messages.length; j++){
var message = messages[j];
// extractDetails(message,folder)
fetchInlineImage(message)
}
}
}
function fetchInlineImage(message) {
var msg = message;
console.log(message)
var pattern = /<img.*src="([^"]*)"[^>]*>/;
var matches = pattern.exec(msg.getBody());
console.log(matches.length)
if(matches) {
var url = matches[1];
var urlPattern = /^https*\:\/\/.*$/;
// If this matches, that means this was copied and pasted from a browser and it's a
// standard URL that we can urlFetch
if(urlPattern.exec(url)) {
// NO OP!
} else {
// Else this means the user copied and pasted from an OS clipboard and the image
// exists on Google's servers. The image can only be retrieved when logged in. Fortunately,
// if we use URLFetchApp, this will act as a logged in user and be able to URLFetch the image.
// We'll need to prepend a Gmail URL (subject to change)
url = "https://mail.google.com/mail/u/0/" + url;
}
// TODO - there is one more case that we're not covering - embedded images that newsletters use
Logger.log("Fetching image from URL: " + url);
var response = UrlFetchApp.fetch(url);
Logger.log("Response status: " + Utilities.jsonStringify(response.getHeaders()));
var blob = response.getBlob();
Logger.log("Response blob: " + blob.getBytes().length);
Drivefolder.createFile(blob).setName('ss.jpeg')
}
};
Email look like this, with lot of images here and there, and I want to extract each one of them:-
enter image description here
You are trying to access inline images from a GMail message.
When GMail was first introduced there was no ability to access inline images.
In 2012 an Issue:Access to inline images was raised and the script shown in the question was proposed as a workaround. A question was also asked on StackOverflow Parsing inlineImages from Gmail raw content.
These (and some variants) worked for a few years until 2014 when a second Issue:GmailApp.getAttachments Issue was raised.
Workarounds were patchy until 2017 when it was announced that the Issue had been resolved.
In 2018, a new answer was added to the StackOverFlow question. and in 2022 a new StackOverflow question How can I extract inline images from a Gmail email? (all available workarounds do not work anymore) was asked and answered.
In short, the script that you are using is redundant. However, the process to access inline images is simple and straightforward. The key is to examine the body by Regex.
The following script provides a basis for you to identify and log inline images.
Put headers in row 1 of sheet="Images".
A1="ID", B1="Subject", C1="Image"
function so75327302() {
var label = GmailApp.getUserLabelByName ('WHOLESALE REP');
var threads = label.getThreads();
for (var i=0;i<threads.length;i++){
var messages = threads[i].getMessages()
for (m=0;m<messages.length;m++){
// Logger.log("DEBUG: i:"+i+",m:"+m+", subject:"+messages[m].getSubject()+", message ID:"+messages[m].getId())
var body = messages[m].getBody()
var regex1 = RegExp('<img src="([^"]*)"[^>]*>', 'g')
var array1 = new Array
var images = new Array
while ((array1 = regex1.exec(body)) !== null) {
Logger.log("message ID:"+messages[m].getId()+", Subject: "+messages[m].getSubject()+" contains inline images."+ `Found ${array1[0]}`);
images.push([array1[0]])
}
if (images.length > 0){
var ss = SpreadsheetApp.getActiveSpreadsheet()
var sheetName = "Images"
var sheet = ss.getSheetByName(sheetName)
var imageLR = sheet.getLastRow()
sheet.getRange(imageLR+1,1).setValue(messages[m].getId())
sheet.getRange(imageLR+1,2).setValue(messages[m].getSubject())
sheet.getRange(imageLR+1,3,images.length).setValues(images)
}
}
}
}

How to send rich text emails with GmailApp?

I’m trying to send a Google Doc, with all of its formatting, in an email.
function sendGoogleDocInEmail() {
var doc = DocumentApp.openById("example_Id");
var body = doc.getBody();
var text = body.getText();
GmailApp.sendEmail("emailaddress#gmail.com", "Hi", text);
This code works fine, but the email is sent as plain text.
I have descriptive hyperlink text pieces in the Google Doc, and they lose their hyperlinks when converted to plain text.
Is there any way I can keep all of the hypertext formatting when sending the email?
I’ve tried passing the body object to the method instead, but that just sends an email with DocumentBodySection in the body.
Thanks!
Trying using a combination of this script: https://stackoverflow.com/a/28503601/3520117
And then using the htmlBody parameter of the MailApp.sendEmail method.
Untested, but should work:
function emailGoogleDoc(){
var id = DocumentApp.getActiveDocument().getId() ;
var forDriveScope = DriveApp.getStorageUsed(); //needed to get Drive Scope requested
var url = "https://docs.google.com/feeds/download/documents/export/Export?id="+id+"&exportFormat=html";
var param = {
method : "get",
headers : {"Authorization": "Bearer " + ScriptApp.getOAuthToken()},
muteHttpExceptions:true,
};
var html = UrlFetchApp.fetch(url,param).getContentText();
Logger.log(html);
var email = person#domain.tld;
var subject = 'Subject line';
var body = "To view this email, please enable html in your email client.";
MailApp.sendEmail(
email, // recipient
subject, // subject
body, { // body
htmlBody: html // advanced options
}
);
}

automated email sending - variable in Htmlbody

I'am very new in gas.
The scenario is this :
Having a spreadsheet with the list of recipient and their names, I want to automate and customize the body of the email writing on the top "Dear {name}".
How can I pass the variable into the Htmlbody option?
Here is part of the code... Thanks in advance.
var ss = SpreadsheetApp.openById("xxxxxxxxxxxxxxxxxxxx").getSheets()[0];
var rng = ss.getRange(2, 1, ss.getLastRow()-1, 8);
var rngvls = rng.getValues();
//
for (var i = 0 ; i<rngvls.length; i++){
var name= ss.getRange(i + 2, 5, 1, 1).getValue();
GmailApp.sendEmail(dest, ogg, body,{name:nam, attachments: [fail.getAs(MimeType.PDF)], htmlBody : <html><h1>here is the header</h1> and here the name
</html>});
The values are already in rngvls. Using the method getValue() in a loop isn't very good for performance.
You can add the name to a string containing the html using concatenation.
Try this:
for (var i = 0 ; i<rngvls.length; i++){
var name = rnglvls[i+1][4];
var html = "<html><h1>here is the header</h1>"+name+"html";
GmailApp.sendEmail(dest, ogg, body,{name:nam, attachments: [fail.getAs(MimeType.PDF)], htmlBody : html});
}
You can pass HTML formatting into the script by setting an HTML variable and then using that variable in the optional MailApp arguments. You can also use other variables within the body using this approach.
It should be noted that the GmailApp class is more likely to require a re-authorization because it can access a user's inbox, so if all you're doing is sending mail the MailApp class is the recommended approach.
var1 = ...
var2 = ...
var3 = ...
var html = '<body>' +
'<p>Message.</p>' +
'<p><b>Variable 1: </b>' + var1 + '</p>' +
'<p><b>Variable 2: </b>' + var2 + '</p>' +
'<p><b>Variable 3: </b>' + var3 + '</p>' +
'</body>';
MailApp.sendEmail(recipient, subject, {htmlBody:html});
Use the Drive service and get the export link.
var url = "https://docs.google.com/feeds/download/documents/export/Export?id="+docid+"&exportFormat=html";
var param = {
method : "get",
headers : {"Authorization": "Bearer " + ScriptApp.getOAuthToken()}
};
var htmlBody = UrlFetchApp.fetch(url,param).getContentText();
}

Here is a script that you can use if you don't need to send too many emails messages (because it's rather slow), it uses a Google doc as a template with a few placeholders and creates a temporary copy of it that is converted to HTML and sent as a message body.
All the features available in Google docs are correctly translated in HTML, including images, fonts etc...
Some formatting are slightly modified (image alignment for example) but nothing to really worry about.
If you are planning to send many messages you might need to create an automated process to send the messages in smaller bunches on a timer trigger but that would be out of subject here.
Code :
function customizeHTMLMessage() {
var templateId = '1aZAgVbvZYD1JcoLqv8x-A5knHLrVNOfEyGh_O-06dgg';// the template doc with placeholders
var docId = DriveApp.getFileById(templateId).makeCopy('temp').getId();
var doc = DocumentApp.openById(docId);// the temp copy
var body = doc.getBody();
var items = ['#day#','#starter#','#main course#','#dessert#'];// the placeholders in this example
var values = ['Monday','Smoked fish','Beef steak','ice cream'];
for(var n = 0;n<items.length;n++){
Logger.log(items[n]+' to replace with '+values[n]);// check in the log
body.replaceText(items[n],values[n]);// update the temp doc
}
doc.saveAndClose();// save changes before conversion
var url = "https://docs.google.com/feeds/download/documents/export/Export?id="+docId+"&exportFormat=html";
var param = {
method : "get",
headers : {"Authorization": "Bearer " + ScriptApp.getOAuthToken()}
};
var htmlBody = UrlFetchApp.fetch(url,param).getContentText();
var trashed = DriveApp.getFileById(docId).setTrashed(true);// delete temp copy
MailApp.sendEmail(Session.getActiveUser().getEmail(),'test','html body',{htmlBody : htmlBody});// send to myself to test
}
note : this template doc is shared (view only) you can make a copy to test it.
Edit : screen capture in 2 different mail readers.

(Gmail) Sending emails from spreadsheet. How to add signature with image?

Due to the large amount of emails i'm sending with GMAIL i decided to automatize this process using a script and following this tutorial.Tutorial: Sending emails from a Spreadsheet
The "Message" is being generated by another function i created, called prepareEmails.
The problems are the following:
1) How can i tell prepareEmails to add my personal signature? I can't simply copy its text into that function, because my signature contains an image (for which i have the URL), and i want that image to be into the signature.
2) How can i make my signature BOLD?
Thanks everybody
There is an open Issue 2441 requesting the ability to append gmail signatures to email when using the GMailService. Visit and star it to receive updates.
As #wchiquito suggests, you can craft a script to attach images, producing a signature. You can also use HTML tags such as <B></B> to render text in bold, and so on.
Here's a different approach that will instead use a draft email as a template. This way, you can produce your signature with a variety of fonts and images using the online editor, and end up with a capability similar to automatic signature insertion.
The template needs to be saved in your Drafts folder, and it needs to have a tag indicating where the body of emails should go.
Example
function sendWithTemplate() {
var msgBody = "Test of sending a message using a template with a signature.";
sendGmailTemplate(Session.getActiveUser().getEmail(), 'test', msgBody );
}
Script
/**
* Insert the given email body text into an email template, and send
* it to the indicated recipient. The template is a draft message with
* the subject "TEMPLATE"; if the template message is not found, an
* exception will be thrown. The template must contain text indicating
* where email content should be placed: {BODY}.
*
* #param {String} recipient Email address to send message to.
* #param {String} subject Subject line for email.
* #param {String} body Email content, may be plain text or HTML.
* #param {Object} options (optional) Options as supported by GmailApp.
*
* #returns GmailApp the Gmail service, useful for chaining
*/
function sendGmailTemplate(recipient, subject, body, options) {
options = options || {}; // default is no options
var drafts = GmailApp.getDraftMessages();
var found = false;
for (var i=0; i<drafts.length && !found; i++) {
if (drafts[i].getSubject() == "TEMPLATE") {
found = true;
var template = drafts[i];
}
}
if (!found) throw new Error( "TEMPLATE not found in drafts folder" );
// Generate htmlBody from template, with provided text body
var imgUpdates = updateInlineImages(template);
options.htmlBody = imgUpdates.templateBody.replace('{BODY}', body);
options.attachments = imgUpdates.attachments;
options.inlineImages = imgUpdates.inlineImages;
return GmailApp.sendEmail(recipient, subject, body, options);
}
/**
* This function was adapted from YetAnotherMailMerge by Romain Vaillard.
* Given a template email message, identify any attachments that are used
* as inline images in the message, and move them from the attachments list
* to the inlineImages list, updating the body of the message accordingly.
*
* #param {GmailMessage} template Message to use as template
* #returns {Object} An object containing the updated
* templateBody, attachments and inlineImages.
*/
function updateInlineImages(template) {
//////////////////////////////////////////////////////////////////////////////
// Get inline images and make sure they stay as inline images
//////////////////////////////////////////////////////////////////////////////
var templateBody = template.getBody();
var rawContent = template.getRawContent();
var attachments = template.getAttachments();
var regMessageId = new RegExp(template.getId(), "g");
if (templateBody.match(regMessageId) != null) {
var inlineImages = {};
var nbrOfImg = templateBody.match(regMessageId).length;
var imgVars = templateBody.match(/<img[^>]+>/g);
var imgToReplace = [];
if(imgVars != null){
for (var i = 0; i < imgVars.length; i++) {
if (imgVars[i].search(regMessageId) != -1) {
var id = imgVars[i].match(/realattid=([^&]+)&/);
if (id != null) {
var temp = rawContent.split(id[1])[1];
temp = temp.substr(temp.lastIndexOf('Content-Type'));
var imgTitle = temp.match(/name="([^"]+)"/);
if (imgTitle != null) imgToReplace.push([imgTitle[1], imgVars[i], id[1]]);
}
}
}
}
for (var i = 0; i < imgToReplace.length; i++) {
for (var j = 0; j < attachments.length; j++) {
if(attachments[j].getName() == imgToReplace[i][0]) {
inlineImages[imgToReplace[i][2]] = attachments[j].copyBlob();
attachments.splice(j, 1);
var newImg = imgToReplace[i][1].replace(/src="[^\"]+\"/, "src=\"cid:" + imgToReplace[i][2] + "\"");
templateBody = templateBody.replace(imgToReplace[i][1], newImg);
}
}
}
}
var updatedTemplate = {
templateBody: templateBody,
attachments: attachments,
inlineImages: inlineImages
}
return updatedTemplate;
}
Credit where credit is due: The "Yet Another Mail Merge" script includes code that preserves inline images in emails during a mail merge - I've borrowed from that. Thanks Romain!
Currently the API does not offer anything to include the signature to messages, however, if you have control of the signature, you can use the method sendEmail(recipient, subject, body, options) available in classes GmailApp/MailApp. The options parameter allows you to set additional parameters to get what you need, for example, include images, with which the signature can build manually, and sets text in bold.
I invite you to take a look at the documentation/examples and post any questions you may have. An interesting example can be found here.

Need to edit gdoc using a googleappscript

Is it possible that I could add the body of a gdoc into an email? I kinda have an idea of how to do it but I am not completely sure. I have written this code below to kinda help me. I am new to this and I have managed to have a few scripts running, but I am completely lost on this one. I have watched several videos and this is what I was able to do. The code is below.
Basically what I want to do is to be able to have a user input his name and another variable and then go to the google doc file and change it to the value that was input and then put it back in an email and send it to an address... Any ideas of what I am doing wrong or where should I start?? Thanks in advance.
function gsnot() {
var emailaddress="albdominguez25#gmail.net";
var sub="Subject1";
var pattern = Browser.inputBox("Enter your name");
var pattern2 = Browser.inputBox("Enter the minutes:");
var templateDocID= ScriptProperties.getProperty("EmailTemplateDocId");
var doc = DocumentApp.openById(templateDocID);
var body = doc.getActiveSection()
var html = "";
var keys = {
name: pattern,
min: pattern2,
};
for ( var k in keys ) {
body.replaceText("%" + k + "%", keys[k]);
doc.saveAndClose();
html = getDocAsHtml(docId);
DocsList.getFileById(docId).setTrashed(true);
return html;
var emailaddress="albdominguez25#gmail.net";
var sub="Subject1";
MailApp.sendEmail(emailaddress,sub, {htmlBody: body});}}
You might want to change your code by reading the body from the document into a variable, doing the replace on the variable and inserting that into your email. For example:
function gsnot() {
var emailaddress = "albdominguez25#gmail.net";
var sub = "New Subject";
var pattern = Browser.inputBox("Enter your name:");
var pattern2 = Browser.inputBox("Enter the minutes:");
var templateDocID = ScriptProperties.getProperty("EmailTemplateDocId");
var doc = DocumentApp.openById(templateDocID);
var body = doc.getText();
var replacement;
var k;
var keys = {
name: pattern,
min: pattern2
};
for (k in keys) {
if (keys.hasOwnProperty(k)) {
replacement = new RegExp("%" + k + "%",'g');
body = body.replace(replacement, keys[k]);
}
}
MailApp.sendEmail(emailaddress,sub, '', {htmlBody: body});
}
A few notes:
It is good form to have all your var statements at the beginning of
the function
When you use for-in (eg. for (k in keys) ), it returns all properties of the object. You only want the ones you assigned. This is the reason for: for (k in keys)
You had the mail sending for each property, I believe you wanted it outside the for-in loop so it only sent after all the replacements were completed.
Using replace(), you need to create a regular expression object that is set to global
or it will only replace the first instance of the pattern (you have name twice).
In your parameters for sendEmail(), even if you are using the htmlBody option, you need to specify a plain text body. I used empty quotes ''.