Google Script CacheService cache image for inlineI

2019-02-15 17:42发布

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?

1条回答
手持菜刀,她持情操
2楼-- · 2019-02-15 18:20

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.

查看更多
登录 后发表回答