Copying rich text and images from one document to MIME in another document

I finally got it work. It was much more simple and did not even involve MIME. The trick was to modify the image tags in the working HTML to include the base64 encoded image so that the src tag could use this format (here shown with a gif as example):

src="data:image/gif;base64,<base64 encoded image>"

I already had the code necessary to get the HTML from the rich text field (see my blog post already mentioned in my question). So all I needed was to replace the image src tags with the correct src format including the base64 encoded image.

The following code gets the HTML and goes through each of the included images and modifies the src tag:

String html = this.document.getValue(fieldName).toString();
if (null != html) {
    final List<FileRowData> fileRowDataList = document.getEmbeddedImagesList(fieldName);
    if (null != fileRowDataList) {
        final Matcher matcher = imgRegExp.matcher(html);
        while (matcher.find()) {
            String src =;
            final String srcToken = "src=\"";
            final int x = src.indexOf(srcToken);
            final int y = src.indexOf("\"", x + srcToken.length());
            final String srcText = src.substring(x + srcToken.length(), y);
            for (FileRowData fileRowData : fileRowDataList) {
                final String srcImage = fileRowData.getHref();
                final String cidImage = ((AttachmentValueHolder) fileRowData).getCID();
                final String typeImage = ((AttachmentValueHolder) fileRowData).getType();
                final String persistentName = ((AttachmentValueHolder) fileRowData).getPersistentName();

                // Add base 64 image inline (src="data:image/gif;base64,<name>")
                if (srcText.endsWith(srcImage)) {
                    final String newSrc = src.replace(srcText, "data:" + typeImage + ";base64," + getBase64(persistentName));
                    html = html.replace(src, newSrc);

Here is the getBase64() method that base64 encodes an image:

private String getBase64(final String fileName) {
    String returnText = "";
    try {
        BASE64Encoder base64Enc = new BASE64Encoder();
        ByteArrayOutputStream output = new ByteArrayOutputStream();
        base64Enc.encode(this.getEmbeddedImageStream(fileName), output);
        returnText = output.toString();
    } catch (NotesException e) {
    } catch (IOException e) {

    return returnText;

Some of the code is from the emailBean by Tony McGuckin.

Leave a Comment