使用Groovy和Apache commons从base64字符串发送图像附件

时间:2017-03-14 21:46:55

标签: groovy base64 mime apache-commons

我正在编写一个流程,以便在使用Groovy的系统中向客户发送电子邮件,并且已经安装了apache.commons.mail.*个库(尽管如果绝对必要,我可以安装其他库)。

问题是图像作为base64编码的字符串传递给我。我已经考虑将它们保存为图像,然后通过URL(here are some examples of sending an email with attachments)附加它们,但似乎浪费了解码它们以重新编码的步骤。有没有办法直接附加图像?

我找到了a few其他SO postssimilar questions,但他们似乎对我的情况给出了一个令人不满意的答案,或者依赖于我没有的其他Java版本/库访问。

编辑:

现在我在这里(感谢JerryP对this post的评论):

def my_img = "data:image/jpeg;base64,/9j/4AAQSkZJRgABAQAAAQAB...";
byte[] img_bytes = b64_data.src.drop(b64_data.src.indexOf(',')+1).decodeBase64();  // This extracts the encoded part
def type = b64_data.src.substring(b64_data.src.indexOf(':') + 1, b64_data.src.indexOf(';') ); // This extracts the data type from the long base64 string (i.e. 'data:image/jpeg;base64,/9j/4AAQSkZJRgABA...')

enc_attachments = ByteArrayDataSource( img_bytes, type ); 

所以,我现在有ByteArrayDataSource我的图像,但the embed calls in apache commons不将ByteArrayDataSource作为参数。

1 个答案:

答案 0 :(得分:0)

好的,我明白了。以上实际上是有效的,我只是错过了新的' ByteArrayDataSource之前的关键字,所以当我发送时它给了我一些奇怪的东西。所以最终的代码是这样的:

def my_img = "data:image/jpeg;base64,/9j/4AAQSkZJRgABAQAAAQAB...";
def filename = "foo.jpg";
byte[] img_bytes = my_img.drop(my_img.indexOf(',')+1).decodeBase64();  // This extracts the encoded part
def type = my_img.substring(my_img.indexOf(':') + 1, my_img.indexOf(';') ); // This extracts the data type from the long base64 string (i.e. 'data:image/jpeg;base64,/9j/4AAQSkZJRgABA...')

enc_attachment = new ByteArrayDataSource( img_bytes, type );

// ... set up email stuff here

def cid = email.embed(enc_attachment, filename);
attachment_str += '<img src="cid: ' + cid + '" />';  // email.embed() returns a random 'cid'
// put attachment_str in your message before sending in order to embed.