java mail Base64 encoded string to image attachment

java send email with attachment
base64 to file java
how-to-send-email-with-embedded-images-using-java
java base64 decode
spring boot send email with image
outlook base64 image
inline embedding base64 encoding
gmail base64 image

I have a base64 encoded string which is posted using JSON into a Spring form.

data:image/png;base64,iVBORw0KGg......etc

I want to add this image as an attachment to an email. Attaching the file works fine, but it is just adding the base64 string as the attachment.

I am using the following code to create the attachment part.

private MimeBodyPart addAttachment(final String fileName, final String fileContent) throws MessagingException {

    if (fileName == null || fileContent == null) {
        return null;
    }

    LOG.debug("addAttachment()");

    MimeBodyPart filePart = new MimeBodyPart();

    String data = fileContent;
    DataSource ds;
    ds = new ByteArrayDataSource(data.getBytes(), "image/*");

    // "image/*"
    filePart.setDataHandler(new DataHandler(ds));
    filePart.setFileName(fileName);

    LOG.debug("addAttachment success !");

    return filePart;

}

I also tried

 ds = new ByteArrayDataSource(data, "image/*");

How can I convert the base64 string into a proper image file using the ByteArrayDataSource ?

You'll hav to use a Base64-decoder first. With Java 8 you could do:

byte[] imgBytes = Base64.getDecoder().decode(base64String);

With older java-versions you'll have to use some library like apache commons-codec or something - there's lots of those around.

How to attach base64 image in mail to JavaMail and , Try: helper.addAttachment("MyImageName.jpg", new ByteArrayResource(value.​getBytes()));. But please read: From the code, it looks like you  I need to send an image as part of email body using java :-The Steps I followed is as below. Take an image and encode it using org.apache.commons.codec.binary.Base64 and use it in html as image src tag. Decode the encoded image and send using the mailer API.

To avoid decoding and re-encoding you can use the javax.mail.internet.PreencodedMimeBodyPart to load your base64 string and attach the PreencodedMimeBodyPart to your message.

    private MimeBodyPart addAttachment(final String fileName, final String fileContent) throws MessagingException {
        if (fileName == null || fileContent == null) {
            return null;
        }

        LOG.debug("addAttachment()");
        MimeBodyPart filePart = new PreencodedMimeBodyPart("base64");
        filePart.setContent(fileContent, "image/*");
        LOG.debug("addAttachment success !");
        return filePart;
    }

Otherwise, you can use the javax.mail.internet.MimeUtility::decode to wrap the input stream used with your data source but this will decode and re-encode the given data.

    private MimeBodyPart addAttachment(final String fileName, final String fileContent) throws MessagingException {
        if (fileName == null || fileContent == null) {
            return null;
        }

        LOG.debug("addAttachment()");
        MimeBodyPart filePart = new MimeBodyPart();

        String data = fileContent;
        DataSource ds;  //Assuming fileContent was encoded as UTF-8.
        InputStream in = new ByteArrayInputStream(data.getBytes("UTF-8"));
        try {
            in = MimeUtility.decode(in, "base64");
            try {
                ds = new ByteArrayDataSource(in , "image/*");
            } finally {
                in.close();
            }
        } catch (IOException ioe) {
            throw new MessagingException(fileName, ioe);
        }

        // "image/*"
        filePart.setDataHandler(new DataHandler(ds));
        filePart.setFileName(fileName);

        LOG.debug("addAttachment success !");
        return filePart;
    }

javax.mail.internet.MimeBodyPart.setContentID java code examples , onNotification() String fileName = new File(attachmentUrl. addHeader("​Content-Transfer-Encoding", "base64"); MimeBodyPart imagePart = new MimeBodyPart(headers, Sending mail along with embedded image using javamail. String  But this gives me the base64 encoded string in the body of the mail. Is there any way out to attach the image as a attachment in mail using javascript,php,jquery or anything else?? php javascript jquery canvas mailto

 // v = data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAA........................
String body = v.replace("data:image/png;base64","");                                    
MimeBodyPart filePart = new PreencodedMimeBodyPart("base64");
filePart.setFileName("screenshot.png");
//This is Needed if you want to show as an html element in the page
filePart.setHeader("Content-ID", "<screenshot>");
filePart.setText(body);
message.getMimeMultipart().addBodyPart(filePart);

JavaMail - How to insert images into email for sending, JavaMail code example to insert images into emails for sending. In the tutorial Send e-mail with attachment in Java, we discussed Where htmlMessage is a String represents content of the message with HTML tags: Then the image part should be created as follows: Coding An Email Utility class. When you put it into a variable of type string, it will do that. If you want to put that in a variable you should use the binary() function. Wrap the attachment content in the binary() function and add the expression in the variable.

i encounter the same issue and I was able to fix it using this code:

//you have to parse the data first to remove "data:image/png;base64" before you can use the decodeBase64(data).

byte[] imgBytes = Base64.decodeBase64(data);
ByteArrayDataSource dSource = new ByteArrayDataSource(imgBytes, "image/*");

Send email with an attachment, In this example, we are sending as attachment this image : void sendMail(​String mailServer, String recipient) { System.out.println("Send mail with attached file  Base64 Encoding of a File to a String [UTF-8] Email attachment search. XML, node's content as Zip file Base64 encoded. attachment binary data in MIME body. Image in Email Handled as Attachment and not Related Data? decrypting saml with ssl. How to encode base 64 html body? Base64 encoded mail with SMTP/PHP. Soap with attachment

With the answer of @jmehrens I was able to attach a file, but they couldn't be opened. Turned out you need to set the datatype seperately and remove it from the given fileContent String:

{
   String dataType = StringUtils.substringBetween(file, "data:", ";base64,"); // extract data type (dataType = "image/png") 
base64EncodedFileContent = fileContent.replaceFirst("data:.*;base64,", ""); // remove prefix from fileContent String (base64EncodedFileContent = "iVBORw0KGg......etc"

    MimeBodyPart filePart = new PreencodedMimeBodyPart("base64");
    filePart.setContent(base64EncodedFileContent, dataType);
    filePart.setFileName(fileName);

    return filePart;
 }

JavaMail FAQ, How do I read a message with an attachment and save the attachment? I have data that's already encoded in (e.g.) base64, how do I tell JavaMail to send this data String host = "smtp.gmail.com"; String username = "user"; String password Another approach is to include the image data inline in the html content of the  import java.io.*; public class MIMEBase64 { /* Base64 uses a 65 character subset of US-ASCII, allowing 6 bits for each character so the character "m" with a Base64 value of 38, when represented in binary form, is 100110.

How to Send an Email using Java MailAPI with Large Image as an , The JavaMail API provides a platform-independent and protocol-independent framework to build You must have seen so many emails that have image attachments and are also used in the email message. final String sourceEmail = "<Your Gmail Email ID"; // requires valid Gmail id Content-Transfer-Encoding: base64 You will have added a base64 string as an attachment with the above code, which means you would need to save the attachment and decode it at the other end. I think you may have really wanted to do this: email.addFile({ filename: 'my-file.pdf', content: new Buffer(aBase64EncodedPDF, 'base64'), contentType: 'application/pdf', });

Java Code Examples javax.mail.util.ByteArrayDataSource, This page provides Java code examples for javax.mail.util. withAttachment("​dresscode.txt", new ByteArrayDataSource("Black Tie Optional", protected String populateContentOnBodyPart(BodyPart part, getAttachments()) { // Decode base64 encoded data byte[] data = Base64. assertEquals("image/jpeg​", dr. In the tutorial Send e-mail with attachment in Java, we discussed how to attach files to an e-mail message using JavaMail.In this article, we will use a similar technique plus some modification in order to embed some images directly into the message.

JavaMail API - Sending Email With Inline Imagess, // first part (the html) BodyPart messageBodyPart = new MimeBodyPart(); String htmlText = "<H1>Hello</H1><img src=\"cid:image\">"; messageBodyPart. Salesforce Attachment Body Base64 - Online base64, base64 decode, base64 encode, base64 converter, python, to text _decode decode image, javascript, convert to image, to string java b64 decode, decode64 , file to, java encode, to ascii php, decode php , encode to file, js, _encode, string to text to decoder, url characters, atob javascript, html img, c# encode, 64 bit decoder, decode linuxbase

Comments
  • cool, I will try this: byte[] blah = Base64.decodeBase64(data.getBytes());
  • hi Coen.. did it work for you? I tried this one but i got an empty image in my email.
  • Welcome to Stack Overflow! Please try to provide a nice description about how your solution works. See: How do I write a good answer? Thanks