sendmail中inlineImages的Google Script CacheService缓存图像 [英] Google Script CacheService cache image for inlineImages in sendMail
问题描述
我想将图像存储在Google Script的Cacheservice中,然后再将该图像作为内嵌图像插入HTML邮件中.
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.
我已经尝试使它起作用,但是到目前为止没有成功. Logger中以下代码的错误是无效参数:附件".如果我检查它在sendMail()中显示的var图标是一个斑点:
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 缓存服务仅接受 string 值,而您试图将blob推入显然是不同类型的值.一旦将其转换为正确的字符串,就可以了.
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.
为了确保我们正确保存它,我们应该使用base64encode.
To ensure that we save it correctly we should use base64encode.
尝试替换
var cache = CacheService.getDocumentCache().put('icon', icon);
与
var cache = CacheService.getDocumentCache()
cache.put('icon', Utilities.base64Encode(icon.getBytes()));
分别,当您获取缓存值时,您将需要从我们的字符串中创建一个新的blob对象.
And respectively, when you are getting cached value back you will need to create a new blob object from our string.
首先,我们创建一个空的blob并读取缓存的值:
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.
这篇关于sendmail中inlineImages的Google Script CacheService缓存图像的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!