java.io.IOException: "text/plain" DataContentHandler 需要 String 对象,被赋予了类 [B

Posted

技术标签:

【中文标题】java.io.IOException: "text/plain" DataContentHandler 需要 String 对象,被赋予了类 [B【英文标题】:java.io.IOException: "text/plain" DataContentHandler requires String object, was given object of type class [B 【发布时间】:2018-09-07 13:47:37 【问题描述】:

当我尝试发送一个附件时,无论是 zip 文件还是文本文件,代码都可以正常工作,但是当我尝试发送两个附件时,一个是文本文件,另一个是 Zip 文件,它会抛出错误。我尝试了多种方法,但仍然没有运气。

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);   

例外:

 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)

【问题讨论】:

如何发送带有 text/plain 类型的附件? 查看这个帖子***.com/questions/4612673/…也许对你有帮助。 【参考方案1】:

如果您有存储在字节数组中的数据,请使用ByteArrayDataSource 将其作为部件的内容提供:

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());

【讨论】:

以上是关于java.io.IOException: "text/plain" DataContentHandler 需要 String 对象,被赋予了类 [B的主要内容,如果未能解决你的问题,请参考以下文章

java.io.IOException: toDerInputStream 拒绝标签类型 77

java.io.IOException:系统找不到指定的路径

java.io.IOException: Connection reset by peer和java.io.IOException: Connection timed out。Socket

android java.io.IOException:传输端点未连接

任务 ':app:compileDebugKotlin' java.io.IOException 执行失败

火花:java.io.IOException:设备上没有剩余空间[再次!]