Skip to content

Instantly share code, notes, and snippets.

@rgambelli
Created December 11, 2017 09:05
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save rgambelli/099b48a513bb4f8f4a30d63cb662eaa1 to your computer and use it in GitHub Desktop.
Save rgambelli/099b48a513bb4f8f4a30d63cb662eaa1 to your computer and use it in GitHub Desktop.
Find data:image in email html body, decode, embed and replacing them with <img src="cid:...", return the new html body
private String replaceImgPattern(ImageHtmlEmail imageHtmlEmail, String html) {
Matcher matcher = IMG_PATTERN.matcher(html);
// Used to name the embedded images
int i = 0;
while (matcher.find()) {
// in the RegEx we have the <src> element as second "group"
String srcAttribute = matcher.group(2);
if (srcAttribute.startsWith("data:image")) {
// This extracts the encoded part
String bytes = StringUtils.substringAfter(srcAttribute, ",");
// This extracts the data type from the long base64 string (i.e. 'data:image/jpeg;base64,/9j/4AAQSkZJRgABA...')
String type = StringUtils.substringBetween(srcAttribute, ":", ";");
if (StringUtils.isBlank(bytes) || StringUtils.isBlank(type)) {
logger.warn("Skipping base64 encoded image because of incomplete data, bytes or type were not found");
continue;
}
byte[] decoded = Base64.getDecoder().decode(bytes);
logger.debug("Creating ByteArrayDataSource for a base64 encoded image of {} bytes and type {}", decoded.length, type);
ByteArrayDataSource bads = new ByteArrayDataSource(decoded, type);
try {
String cid = imageHtmlEmail.embed(bads, String.valueOf(i));
// String cid = email.embed(tempFile);
String replacement = "cid:" + cid;
logger.debug("Embedded just decoded base64 encoded image, its cid is {} and was named {}, replacing the encoded one with this now", cid, i);
html = StringUtils.replace(html, srcAttribute, replacement);
} catch (EmailException ex) {
logger.error("The embedding has failed, its name would have been " + i, ex);
}
}
i++;
}
return html;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment