问题
I want to send a pdf file in an email with javax mail.
Below, baos is a ByteArrayOutputStream.
byte [] data= baos.toByteArray();
OutputStream output = new FileOutputStream(fileName);
output.write(data);
output.close();
DataSource source = new FileDataSource(fileName);
attachBodyPart.setDataHandler(new DataHandler(source, "application/pdf"));
attachBodyPart.setFileName(fileName);
multipart.addBodyPart(attachBodyPart);
message.setContent(multipart, "text/html");
Transport transport = session.getTransport("smtp");
transport.connect(host, from, pass);
transport.sendMessage(message, message.getAllRecipients());
transport.close();
I am getting this exception when I try to send the email :
javax.mail.MessagingException: IOException while sending message;
nested exception is: javax.activation.UnsupportedDataTypeException: no object DCH for MIME type application/pdf
I don't know what's wrong here.
If someone does...
Thanks in advance.
回答1:
Try this.
MimeBodyPart attachment = new MimeBodyPart();
DataSource dataSrc = new ByteArrayDataSource(baos.toByteArray(), "application/pdf");
attachment.setDataHandler(new DataHandler(dataSrc));
attachment.setFileName("myPdfDocument.pdf");
multipart.addBodyPart(attachment);
回答2:
Everytime I do this I use byte array directly without working through file:
byte [] data = baos.toByteArray();
MimeBodyPart attachBodyPart = new MimeBodyPart();
attachBodyPart.setFileName(fileName);
attachBodyPart.setDisposition(MimeBodyPart.ATTACHMENT);
attachBodyPart.setContent(data, "application/pdf");
multipart.addBodyPart(attachBodyPart);
来源:https://stackoverflow.com/questions/33933145/jave-email-with-pdf-attached-file-no-object-dch-for-mime-type-application-pd