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.
Related
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}
});
}
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
});
}
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
}
);
}
I have a script that produces an automated email from cell content in a Google Sheet. Is it possible to restrict the width of a cell's output in the email, forcing the text to wrap? I have tried using textarea tags as follows:
+ <textarea rows="4" cols="20">
+ sheet.getRange(6,9,1,1).getValue()
+ </textarea>
However, this simply outputs as "+ sheet.getRange(6,9,1,1).getValue() +" (i.e. it doesn't generate the cell content).
Is this possible?
Here's how I have built the script:
function EmailFormConfirmation() {
var ss = SpreadsheetApp.getActiveSpreadsheet();
Utilities.sleep(60000);
var sheet = ss.getSheetByName("Form responses");
var lock = LockService.getPublicLock();
lock.waitLock(60000);
lock.releaseLock();
var email = sheet.getRange(2,9,1,1).getValue();
var message = "<HTML><BODY>"
+ "<P >Hi "
+ sheet.getRange(4,9,1,1).getValue()
+ ","
etc.
EDIT The below produces the cell content, but doesn't wrap the text.
var htmlMsg = "<HTML><BODY>"
+ "<textarea rows='4' cols='10'>"
+ sheet.getRange(6,9,1,1).getValue()
+ "</textarea>"
+ "</HTML></BODY>";
MailApp.sendEmail(email, "LMI Request", "", {htmlBody: htmlMsg});
To respond to the question re: textbox, the following did as you requested
var htmlMsg = "<HTML><BODY>"
+ "<textarea rows='4' cols='20'>"
+ sheet.getRange(6,9,1,1).getValue()
+ "</textarea>"
+ "</BODY></HTML>";
GmailApp.sendEmail("m....l#gmail.com", "subject","hi" , {htmlBody: htmlMsg});
note how the single and double quotes are used.
Here is an example of how you can use templates to build your email responses. The documentation can be found here:
https://developers.google.com/apps-script/guides/html/templates
In code.gs
function myFunction(){
var sheet = SpreadsheetApp .....
var value = sheet.getRange(6,9,1,1).getValue();
var emailHtml = buildTemplate(value);
GmailApp.sendEmail("person#example.com", "subject","Hello", {htmlBody: emailHtml});
}
function buildTemplate(values){
var template = HtmlService.createTemplateFromFile('emailTemplate');
template.tmpValues = values;
return template.evaluate().getContent();
}
in emailTemplate.html
<html>
<body>
<textarea rows='4' cols='20'>
<?=tmpValues?>
</textarea>
</body>
</html>
I've search high and low for an answer but without an y luck. Got a Google spreadsheet which uses apps script to connect to a database to pull in some raw data into a spreadsheet. I then use various spreadsheet formulas to manipulate that data and then final create a chart.
My next challenge is that I want to be able to embed that chart into an email via apps script and send it as an HTML email..
Is this at all possible or should I start looking for some other solution?
Thanks!
Mikael
Here is the code I used to email charts.
Please note that you need to give everyone with the link access to the spreadsheet. If not, you'll get an image in the email stating user is not signed in. (very annoying that there's no workaround to this)
function emailCharts(sheet,emails,emailSubject){
var charts = sheet.getCharts();
if(charts.length==0){
MailApp.sendEmail({
to: emails,
subject: "ERROR:"+emailSubject,
htmlBody: "No charts in the spreadsheet"});
return;
}
var chartBlobs=new Array(charts.length);
var emailBody="Charts<br>";
var emailImages={};
for(var i=0;i<charts.length;i++){
chartBlobs[i]= charts[i].getAs("image/png").setName("chartBlob"+i);
emailBody= emailBody + "<img src='cid:chart"+i+"'><br>";
emailImages["chart"+i]= chartBlobs[i];
}
MailApp.sendEmail({
to: emails,
subject: emailSubject,
htmlBody: emailBody,
inlineImages:emailImages});
}
Make the spreadsheet Public and run the script. Modified version of the script pasted below with comments
enter code here function
emailCharts(sheet,emails,emailSubject){
var targetspreadsheet = SpreadsheetApp.getActiveSpreadsheet(); // Active spreadsheet of the key file
var sheet = targetspreadsheet.getSheetByName('Sheet1'); // Change the sheet name
var emailSubject = 'test';
var emails = 'test#test.com'; // your email ID
var charts = sheet.getCharts();
if(charts.length==0){
MailApp.sendEmail({
to: emails,
subject: "ERROR:"+emailSubject,
htmlBody: "No charts in the spreadsheet"});
return;
}
var chartBlobs=new Array(charts.length);
var emailBody="Charts<br>";
var emailImages={};
for(var i=0;i<charts.length;i++){
var builder = charts[i].modify();
builder.setOption('vAxis.format', '#');
var newchart = builder.build();
chartBlobs[i]= newchart.getAs('image/png');
emailBody= emailBody + "<p align='center'><img src='cid:chart"+i+"'></p>";
emailImages["chart"+i]= chartBlobs[i];
}
MailApp.sendEmail({
to: emails,
subject: emailSubject,
htmlBody: emailBody,
inlineImages:emailImages});
}
As the Charts Service appears to only be a partial implementation of EmbeddedChart used in SpreadsheetApp Service not all of the ChartTypes and options are implemented, meaning charts might render differently than they do in Google Sheets. The modified version of the previous answer below will mean charts are included in emails as images as they appear in Google Sheets. As this solution also uses an authentication token generated by the script the view permissions on the Google Sheet does not have to be changed.
// Based on https://stackoverflow.com/a/22200230/1027723
function emailChartUsingImageUrl(){
const idt = SpreadsheetApp.getActive().getId();
const sheet = SpreadsheetApp.getActiveSheet();
const charts = sheet.getCharts();
// setup some variables for our email
const chartBlobs = new Array();
const emailImages = {};
let emailBody = "Charts<br>";
// setup our call to fetch the chart image
const token = ScriptApp.getOAuthToken(); // project requires https://www.googleapis.com/auth/spreadsheets scope
const baseUrl = `https://docs.google.com/spreadsheets/d/${idt}/embed/oimg?access_token=${token}&disposition=ATTACHMENT&bo=false&filetype=png&oid=`;
// for each chart fetch the download image as a blob and appended to our email body
charts.forEach(function(chart, i){
// NEW BIT
const url = baseUrl + chart.getChartId();
chartBlobs[i] = UrlFetchApp.fetch(url).getBlob();
emailBody += "<p align='center'><img src='cid:chart"+i+"'></p>";
emailImages["chart"+i]= chartBlobs[i];
});
// Send email with inline images
MailApp.sendEmail({
to: "me#example.com",
subject: "Email Charts - get chart from image url",
htmlBody: emailBody,
inlineImages:emailImages});
}