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



当我尝试发送一个附件时,这是在投掷错误。我已经尝试了多种方法,但仍然没有运气。

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)

如果您的数据存储在字节数组中,请使用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());

相关内容

  • 没有找到相关文章

最新更新