smtpjakarta-mailmime-typesmime-messagemime-mail

java.io.IOException: "text/plain" DataContentHandler requires String object, was given object of type class [B


When I'm trying to send one attachment, what ever zip file or text file, code is working fine but when trying to send two attachments one is Text file and other one is Zip file, it is throwing error. I have tried number of ways but still no luck.

MimeMessage msg = new MimeMessage(session){
msg.addHeader("Content-type", directMessage.getBody().getContentType());
msg.addHeader("Content-Transfer-Encoding", "8bit");
msg.setFrom(new InternetAddress(fromaddress));
msg.setSubject(directMessage.getSubject(), "UTF-8");
MimeMultipart mp = new MimeMultipart();
BodyPart bodyPart = null; 
for(int i=0;i<directMessage.getAttachments().size();i++){

    bodyPart = new MimeBodyPart();
    bodyPart.setContent(Base64.decodeBase64(directMessage.getAttachments().get(i).getContent().getBytes()),directMessage.getAttachments().get(i).getContentType());
    bodyPart.setDisposition(decryptedMessage.getBodyPart(0).getDisposition());
    bodyPart.setFileName(directMessage.getAttachments().get(i).getFilename());
    mp.addBodyPart(bodyPart);
    mp.setSubType("multipart/mixed");
}
msg.setContent(mp);
msg.setSentDate(new Date());
msg.setRecipients(Message.RecipientType.TO, InternetAddress.parse(toaddress, false));
Transport.send(msg);   

Exception:

 javax.mail.MessagingException: IOException while sending message;
  nested exception is:
    java.io.IOException: "text/plain" DataContentHandler requires String object, was given object of type class [B
    at com.sun.mail.smtp.SMTPTransport.sendMessage(SMTPTransport.java:1167)
    at javax.mail.Transport.send0(Transport.java:195)
    at javax.mail.Transport.send(Transport.java:124)

Solution

  • If you have data that's stored in a byte array, use ByteArrayDataSource to supply it as the content of a part:

    bodyPart = new MimeBodyPart();
    DataSource ds = new ByteArrayDataSource(
        Base64.decodeBase64(directMessage.getAttachments().get(i).getContent().getBytes()),
        directMessage.getAttachments().get(i).getContentType());
    bodyPart.setDataHandler(new DataHandler(ds));
    bodyPart.setDisposition(decryptedMessage.getBodyPart(0).getDisposition());
    bodyPart.setFileName(directMessage.getAttachments().get(i).getFilename());