Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Google Script CacheService cache image for inlineImages in sendMail

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 = '[email protected]';
  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 = '[email protected]';
      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?

like image 300
Fabian Avatar asked May 25 '26 04:05

Fabian


1 Answers

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

var cache = CacheService.getDocumentCache().put('icon', icon);

with

var cache = CacheService.getDocumentCache()
cache.put('icon', Utilities.base64Encode(icon.getBytes()));

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:

var iconBlob = Utilities.newBlob("")
var cachedValue = cache.get('icon');

And then you can use it like:

iconBlob.setBytes(Utilities.base64Decode(cachedValue ))
iconBlob.setName('yourname')
iconBlob.setContentType('image/png')

You can check both methods in reference. You can also save Objects in Cache Service the same way if you Stringify them.

like image 159
Evgeny Vostok Avatar answered May 26 '26 22:05

Evgeny Vostok



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!