lucky Barkane
lucky Barkane

Reputation: 77

How to attach base64 image in mail to JavaMail and MimeMessageHelper?

I am trying to send the Mime email with an image attachment but do know how to do this. I tried the online solution but did not work. I will get the encoded image and need to decode and attach in the mail. This is my code

public class SendEmail{

public static void main( String[] args ) throws javax.mail.MessagingException, IOException
{  

    String value= "Wyk+HjAxHTAyNzg3MDUdODQwHTAxOR0wMDAwMDAwMDAwMDAwMDAd" +
            "RkRFQh0wMDAwMDAwHTA0MB0dMS8xHTUwLjVMQh1OHVcgMzR0aCBTdHJlZXQdQ" +
            "XVzdGluHVRYHSAeMDYdMTBaR0QwMDQdMTFaUmVjaXBpZW50IENvbXBhbnkgTmFt" +
            "ZR0xMlo5MDEyNjM3OTA2HTE0WioqVEVTVCBMQUJFTCAtIERPIE5PVCBTSElQKio" +
            "dMjNaTh0yMlocWR0yMFogHDAdMjZaNjEzMxwdHgQ=";     

      JavaMailSender mailSender = getJavaMailSender();

    MimeMessage mimeMessage = mailSender.createMimeMessage();
    MimeMessageHelper helper;
    Map<String,Object> map = new HashMap<>();

    try{
        helper = new MimeMessageHelper(mimeMessage, true, "utf-8");
        String sendTo = "[email protected]";
        String htmlMsg = "<h1> hello </h1>";

        mimeMessage.setContent(htmlMsg, "text/html");

        // add attachment encode in base64
        byte[] decodedImg  Base64.decodeBase64(value);
        // dont know how to attache the decode img 


        helper.setTo(sendTo);
        helper.setSubject("Subject");
        mailSender.send(mimeMessage);
    } catch (MessagingException e) {
        e.printStackTrace();
    }



}

Upvotes: 4

Views: 5451

Answers (4)

Joop Eggen
Joop Eggen

Reputation: 109532

This proposal to use embedded Base64 images is said to not being supported everywhere

Adding as attacment is already answered. Alternatively embedding the image works as follows:

htmlMsg += "<img width=\"400\" height=\"400\" "
    + "alt=\"View of the object.\" src=\"data:image/jpeg;base64,"
    + value + "\">";

were value is the Base64 data, the mime type image/jpeg width and height must be adapted.

Some mail recipients may suppress rich text mails in favor of plain text, but as long as the <img> does not refer into the www (confirming you opened the e-mail), the rich text version is okay.

Upvotes: 1

Waqas Ahmed
Waqas Ahmed

Reputation: 5129

Below is the piece of code for sending base64 encoded string(image) as an attachment using java mail api.

@Autowired
private JavaMailSender emailSender;

public void sendMessageWithAttachment(String from,String replyTo, String to, String cc, String subject,  String emailContent, String base64EncodedString) {

MimeMessage message = emailSender.createMimeMessage();
MimeMessageHelper helper = new MimeMessageHelper(message, true);

helper.setFrom(from);
helper.setReplyTo(replyTo);
helper.setTo(to);
helper.setCc(cc);
helper.setSubject(subject);
helper.setText(emailContent, true);

// Use MimeDecoder for decoding in order to avoid illegal argument exception
byte[] imgBytes = Base64.getMimeDecoder().decode(base64EncodedString);
ByteArrayDataSource dSource = new ByteArrayDataSource(imgBytes, "image/*");
helper.addAttachment("AttachedFile.jpg", dSource);
emailSender.send(message);

}

Upvotes: 1

Chamod Pathirana
Chamod Pathirana

Reputation: 758

After modifying the code by bellow code,my issue was solved.

value= value.replaceFirst("^data:image/[^;]*;base64,?", "");
byte[] bytes = javax.xml.bind.DatatypeConverter.parseBase64Binary(value);
helper.addAttachment("MyImageName.jpg", new ByteArrayResource(bytes));

Upvotes: 1

Itamar Kerbel
Itamar Kerbel

Reputation: 2568

Try:

helper.addAttachment("MyImageName.jpg", new ByteArrayResource(value.getBytes()));

But please read: From the code, it looks like you already encoded the image. The "value" seems to be of Base64 format. You should not deal with that as it is done for you.

// you can attach a file directly to the helper
FileSystemResource file = new FileSystemResource(new File("image_file.jpg"));
helper.addAttachment("MyImageName.jpg", file);

If the attachment is not a file on your disk you can use this:

helper.addAttachment("MyImageName.jpg", new ByteArrayResource(IOUtils.toByteArray(attachment)));

if this is an inputstream or this:

helper.addAttachment("MyImageName.jpg", new ByteArrayResource(value.getBytes()));

Upvotes: 4

Related Questions