coding_hero
coding_hero

Reputation: 1769

Send image attachment from base64 string using Groovy and Apache commons

I'm writing a process to send out emails to customers in a system that uses Groovy and has the apache.commons.mail.* libs installed already (although I can install others if absolutely necessary).

The problem is that the images are passed to me as a base64 encoded string. I've considered saving them as an image, and then attaching them via URL (here are some examples of sending an email with attachments) , but it seems like a waste of a step to decode for them to be re-encoded. Is there a way to attach the image directly?

I've found a few other SO posts with similar questions, but they either seem to give an unsatisfactory answer for my situation or rely on other Java versions/libraries I don't have access to.

EDIT:

Here's where I am with it now (thanks to JerryP's comment on 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 ); 

So, I have a ByteArrayDataSource of my image now, but the embed calls in apache commons don't take ByteArrayDataSource as a param.

Upvotes: 2

Views: 970

Answers (1)

coding_hero
coding_hero

Reputation: 1769

Ok, I figured it out. The above actually works, I just missed the 'new' keyword before ByteArrayDataSource, so it was giving me some weirdness when I went to send. So the final code is something like this:

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.

Upvotes: 1

Related Questions