Jave : email with pdf attached file : no object DCH for MIME type application/pdf

蓝咒 提交于 2021-02-05 06:13:05

问题


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

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!