I would like to store an image in Google Script's Cacheservice and then get this image later inserted as an inline image in a HTML mail.
I have tried to make it work, but no success so far. Error of code below in Logger is 'Invalid argument: attachments'. If I check it shows var icon in sendMail() is a blob:
function onOpen(e){
var icon = DriveApp.getFileById('ID').getBlob().setName('icon');
var cache = CacheService.getDocumentCache().put('icon', icon);
}
function sendMail() {
var icon = CacheService.getDocumentCache().get('icon');
var email = 'test@example.de';
var subject = 'test';
var txt = 'test';
var html = '<img src="cid:icon"/>';
MailApp.sendEmail(email, subject, txt, {htmlBody: html, name : 'test', inlineImages:{icon:icon}});
}
Surprisingly if I do this:
function sendMail() {
var icon = DriveApp.getFileById('ID').getBlob().setName('icon');
var email = 'test@example.de';
var subject = 'test';
var txt = 'test';
var html = '<img src="cid:icon"/>';
MailApp.sendEmail(email, subject, txt, {htmlBody: html, name : 'test', inlineImages:{icon:icon}});
}
it works fine. What is the issue with my code?
Google Cache Service accepts only string values, while you are trying to push a blob into it which is apparently different type. Once you turn it to a proper string - it will be fine.
To ensure that we save it correctly we should use base64encode.
Try to replace
with
And respectively, when you are getting cached value back you will need to create a new blob object from our string.
First we create empty blob and read cached value:
And then you can use it like:
You can check both methods in reference. You can also save Objects in Cache Service the same way if you Stringify them.