Script - GmailApp.SendEmail with InlineImages from Google Drive - google-apps-script

Hy, im trying to make a script to send inline images from an alias gmail account. I found most of the code in GmailApp-s documentation, but now im stuck at the last step... Plese plese help, how do i get this part to work?
Thank you!
var html =
'<body>' +
'<img src='cid:image'>' +
'</body>'
function testGmailApp() {
var ImageBlob = DriveApp
.getFileById('0Bx4vy5p9TA6bekY3Q2ZNdzViVkE')
.getBlob()
.setName("ImageBlob");
GmailApp.sendEmail(
'example#gmail.com',
'test GmailApp',
'test',{
htmlBody: html,
inlineImages: {image: ImageBlob}
});
}

Here is how you insert an inline image to your email. You can find an example of this in the documentation for MailApp. In this particular case of sending an inline image, the syntax for both functions remains the same.
As mentioned in the documentation, the first thing step to insert the inline image is to insert an img tag with src =" cid:"Name of the image blob in inlineimages object here"
The html string will look like this:
var html =
'<body>' +
'<h2> Test <img src = "cid:image"> </h2><br />' +
'</body>'
The remaining function remains the same.
Note: src points to cid: image, the name of the key in the inline image object.
Final code:
var html =
'<body>' +
'<h2> Test <img src = "cid:image"> </h2><br />' +
'</body>'
function testGmailApp() {
var ImageBlob = DriveApp
.getFileById('0Bx4vy5p9TA6bekY3Q2ZNdzViVkE')
.getBlob()
.setName("ImageBlob");
GmailApp.sendEmail(
'someone#gmail.com',
'test GmailApp',
'test',{
htmlBody: html,
inlineImages: {image: ImageBlob}
});
}

Related

Convert MailApp.sendEmail code to GmailApp.sendEmail with HTML Body

All, I am looking for help from someone with more experience with this. I have a cobbled together email script that works great as is. I want to specify the from: address using an alias and it's my understanding that I need to use GmailApp vs MailApp to accomplish this. The trouble is, I can't figure out how to make my htmlBody work in the GmailApp version.
Here is my working MailApp code:
function SendPreReleaseAlertEmail(row) {
var sheet = SpreadsheetApp.getActive().getSheetByName('EmailSheet');
var subject = sheet.getRange("M3").getValues(); // Change the subject as needed.
var recipients = sheet.getRange("M2").getValue(); // Change the recipient as needed.
var message = "<HTML><BODY>" + "<P>"
for (var x=6;x<14;x++) { //Loop from * to * with a +1 increment
message = message + sheet.getRange("M" + x).getValues() + "<BR>" //Add row I(x) to the message
}
message = message + "</HTML></BODY>";
MailApp.sendEmail(recipients, subject, "", {htmlBody: message});
}
And this is my FAILED attempt at converting it to GmailApp with a From address:
function SendPreReleaseAlertEmail(row) {
var sheet = SpreadsheetApp.getActive().getSheetByName('EmailSheet');
var subject = sheet.getRange("M3").getValues(); // Change the subject as needed.
var recipients = sheet.getRange("M2").getValue(); // Change the recipient as needed.
var message = "<HTML><BODY>" + "<P>"
for (var x=6;x<14;x++) { //Loop from * to * with a +1 increment
message = message + sheet.getRange("M" + x).getValues() + "<BR>" //Add row I(x) to the message
}
message = message + "</HTML></BODY>";
GmailApp.sendEmail(recipients, subject, {htmlBody: message}, {from: "moo#cow.com"});
}
The above code does in fact email from the alias. But the htmlBody just has the words "[object Object]" in the body of the email.
It's Alive! Here is the final code that solved my problem:
GmailApp.sendEmail(recipients, subject, '', {htmlBody: message, from: "moo#cow.com"});
I think you need to fix two things.
1.The syntax is
sendEmail(recipient, subject, body, options)
So you may need to include a blank placeholder for body in your code.
2.You may also need to have both the htmlBody and from in the options JavaScript object like so:
GmailApp.sendEmail(recipients, subject, '' , {
htmlBody: message,
from: "moo#cow.com"});
You can still use MailApp like that:
var email = "exampleRec#email.com";
var Subject_to_Send = "This is an automated email";
var check_body =
"Good morning team, <br/><br/>"
+"I hope this email finds you well. <br/><br/>";
MailApp.sendEmail( {to:email, subject:Subject_to_Send, body:check_body,htmlBody:check_body, from: "exampleSen#email.com"});
If you also want to send a noReply message you can adjust the last line as follows:
MailApp.sendEmail( {to:email, subject:Subject_to_Send, body:check_body,htmlBody:check_body, noReply: true});

how to put inline image in automated mail from Google sheet

I want to send mail with an inline image instead of as an attachment through google sheet. Please help
the script is as below:
function emailSummary() {
var ss = SpreadsheetApp.getActiveSpreadsheet()
var sh = ss.getSheetByName("Hitesh")
var file = DriveApp.getFileById('1T8QA_WsXQkZZGwmBSN13iPV7rM8xGG_GtYy6T1eug-c')
var gmail = 'hitesh.gtg#Gmail.com';
var html = '<png>'
MailApp.sendEmail("hitesh.gtg#gmail.com", "sunject", "Dear Sir,\n\n Forwarding herewith Monthly Summaryw \n\n Regards \n Hitesh ", {
//email address, subject, message
name: 'Hitesh', //file name
attachments: [file.getAs(MimeType.PDF)] //file to attach
});
}
You can pass HTML to the .sendMail() function. This link to the official documentation includes an example for inline images!
// This code fetches the Google and YouTube logos, inlines them in an email
// and sends the email
function inlineImage() {
var googleLogoUrl = "http://www.google.com/intl/en_com/images/srpr/logo3w.png";
var googleLogoBlob = UrlFetchApp
.fetch(googleLogoUrl)
.getBlob()
.setName("googleLogoBlob");
//You can also get these images from your drive to attach them.
var imgBlob = DriveApp.getFileById("<DRIVE_FILE_ID_OF_PICTURE>")
.getBlob()
.setName("imgBlob");
MailApp.sendEmail({
to: "recipient#example.com",
subject: "Logos",
htmlBody: "inline Google Logo<img src='cid:googleLogo'> images! <br>" +
"img from drive: <img src='cid:driveImg'>"
inlineImages:
{
googleLogo: googleLogoBlob,
driveImg: imgBlob
}
});
}
Emailing Images from your Google Drive
You can use the htmlBody parameter in GmailApp.sendMail(). However, if you want to avoid having to store the image in a URL that is publicly accessible. You can do something like this.
This is a portion of my JavaScript:
function sendImgMsg() {
var fileId=$('#mediaSel').val();//This is the fileId where the image is store. In my image converter script I keep all of this images in the same folder.
google.script.run
.withSuccessHandler(function(fObj){
var msg=$('#emsg').val();//This is the contents of a textarea
var hl='<p>' + msg + '</p><br /><strong>File Name:</strong> '+ fObj.name + '<img src="'+ fObj.uri +'" title="' + fObj.filetype + '" />';
$('#email').css('display','none');
google.script.run.sendImageMessage(hl);//This is the code that sends the email
})
.getSelectedFile(fileId);
}
This is a portion of my html:
<div id="email">
<textarea id="emsg" cols="40" rows="4"></textarea>
<br /><input type="button" value="Send" onClick="sendImgMsg()" />
</div>
This is a portion of my code.gs:
function getSelectedFile(fileId){
var file=DriveApp.getFileById(fileId);
var dataURI=file.getBlob().getDataAsString();
var s=dataURI.split(',')[0];
var mediaType=s.slice(s.indexOf(':')+1,s.indexOf('/'));
var fileType=s.slice(s.indexOf('/')+1,s.indexOf(';'));
var fObj={name:file.getName(),uri:dataURI ,type:mediaType,filetype:fileType};
return fObj;
}
function sendImageMessage(hl) {
GmailApp.sendEmail('recipient', 'ImageInAnEmail', null ,{htmlBody: hl});
}
This is the code that converts external images to imageURI's:
function convImageUrl(url){
var blob=UrlFetchApp.fetch(url).getBlob();
var b64Url='data:' + blob.getContentType() + ';base64,' + Utilities.base64Encode(blob.getBytes());
return b64Url;
}
The above is a part of a script that I use for converting images to imageURI's so that I can store and access them on my Google Drive.

How to remove gridlines from the spreadsheet in google app script

I am trying to write a code in google app script that can mail me the spreadsheet and everything works well. Below is the code I am using.
function convSheetAndEmail(rng, email, subj)
{
var HTML = SheetConverter.convertRange2html(rng);
MailApp.sendEmail(email, subj, '', {htmlBody : HTML});
}
function doGet()
{
// or Specify a range like A1:D12, etc.
var dataRange = SpreadsheetApp.getActiveSpreadsheet().getDataRange()
var emailUser = 'xyz#gmail.com';
var subject = 'Test Email';
convSheetAndEmail(dataRange, emailUser, subject);
}
Now when I am receiving the mail from this script it looks like this
enter image description here
But I don't want to have these Gridlines in my mail. Please advice what I am missing.
Since your are using sheetConverter library. It returns an HTML code with border style element set to 1/1px. So you will have to explicitly replace all the occurrences of border tag in your HTML like so
function convSheetAndEmail(rng, email, subj)
{
var HTML = SheetConverter.convertRange2html(rng)
Logger.log(HTML)
HTML = HTML.replace(' border="1" ',' border="0" ')
HTML = HTML.replace(/border:1px/g,'border:0px')
Logger.log(HTML)
MailApp.sendEmail(email, subj, '', {htmlBody : HTML});
}
Reference:
String.replace()

Send email with picture attachment and body using google script

Hi im having trouble in sending email with image attachment. because the image file name is randomized and have no way to find out if the body of my message fits the image it will send from my drive. Here is a step by step of the process i have done:
online form integration to google spreadsheet (done)
online form to google drive (done) (images from each row of spreadsheet are saved by folder with folder name contains a unique id that is also present in the spreadsheet cell of each row)
What i would like to do here is get the images of folder in google drive by a.(searching the folder name which contains a ceratin text)
b.(getting the folder contents.)(all are images)
c.(attaching the contents of the folder to the email .)
Example:
function send() {
var picture1 = DriveApp.getFilesByName('snottyboy.jpg');
var picture2 = DriveApp.getFilesByName('daryl.jpg');
var recipientsTO = "fgh#gmail.com" + "," + "sdd#gmail.com"+ "," + "spaz#gmail.com"+ "," + "def#gmail.com"+ "," + "abc#gmail.com";
MailApp.sendEmail({
to:recipientsTO,
subject: "LOOK A LIKE",
body:"Final Message",
attachments: [picture1.next(),picture2.next()]
});
}
Thank you for your help.
See image:
To attach a file, you use File.getBlob() to attach it as a blob. For example:
attachments: [picture1.next().getBlob(),picture2.next().getBlob()]
If you know the exact id of a file (e.g. '0BxDqyd_bUCmvN1E3N0dQOWgycEF'), you can get it as a blob like this:
var picture3Blob = DriveApp.getFileById('0BxDqyd_bUCmvN1E3N0dQOWgycEF').getBlob();
Here's a working example:
function sendPics() {
var picture1 = DriveApp.getFileById('0BxDqyd_bUCmvN1E3N0dQOWgycFE'); //public with link
var picture2 = DriveApp.getFileById('0BxDqyd_bUCmvTFNjRkRXbXA2Tms'); //public with link
MailApp.sendEmail({
to: 'testa#example.com, testb#example.com',
subject: "This is a test",
body:"Test message",
attachments: [picture1.getBlob(), picture2.getBlob()]
});
}
and here's an example of the pictures being added inline instead of as attachments:
function sendPicsInline() {
var picture1 = DriveApp.getFileById('0BxDqyd_bUCmvN1E3N0dQOWgycFE'); //public with link
var picture2 = DriveApp.getFileById('0BxDqyd_bUCmvTFNjRkRXbXA2Tms'); //public with link
var inlineImages = {};
inlineImages[picture1.getId()] = picture1.getBlob();
inlineImages[picture2.getId()] = picture2.getBlob();
MailApp.sendEmail({
to: 'testa#example.com, testb#example.com',
subject: "This is a test",
body:"Test message",
htmlBody: 'Test message with pics inline <br>' +
'first:<br><img src="cid:' + picture1.getId() + '" /><br>' +
'second:<br><img src="cid:' + picture2.getId() + '" />',
inlineImages: inlineImages
});
}

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.