[英](Unknown Sender) when sending email with pdf attachment created in iText from java application
[英]Itext PDF attachment in email
我无法打开作为电子邮件附件发送的PDF。 PDF使用iText和Flying Saucer创建,并使用Java中的MimeMessage发送。 我很确定尝试下载附件时存在编码问题,因为在创建PDF时看起来不错。 只是作为附件发送时,打开它存在问题。 例如,在Chrome中,它会发送“无法加载PDF文档”错误。 它在其他浏览器和Adobe Reader中发送类似的错误。 谢谢。
//creates the pdf
DocumentBuilder builder = DocumentBuilderFactory.newInstance().newDocumentBuilder();
byte[] bytes = buf.toString().getBytes("iso-8859-1");
ByteArrayInputStream baos = new ByteArrayInputStream(bytes);
Document doc = builder.parse(baos);
ITextRenderer renderer = new ITextRenderer();
renderer.setDocument(doc, null);
renderer.layout();
OutputStream os = new ByteArrayOutputStream();
os = response.getOutputStream();
renderer.createPDF(os);
os.close();
//email
MimeMessage msg = new MimeMessage(session);
Multipart multipart = new MimeMultipart();
MimeBodyPart messageBodyPart = new MimeBodyPart();
messageBodyPart.setText("This is a test");
multipart.addBodyPart(messageBodyPart);
messageBodyPart = new MimeBodyPart();
//construct the pdf body part
DataSource dataSource = new ByteArrayDataSource(bytes, "application/pdf");
messageBodyPart.setHeader("Content-Transfer-Encoding", "base64");
messageBodyPart.setDataHandler(new DataHandler(dataSource));
messageBodyPart.setFileName("test.pdf");
multipart.addBodyPart(messageBodyPart);
//construct message
msg.setHeader("Content-Type", "multipart/mixed");
msg.setFrom(new InternetAddress(user));
msg.setReplyTo(InternetAddress.parse(replyEmail,false));
msg.setSubject("Test");
msg.setRecipients(Message.RecipientType.TO, to);
msg.setSentDate(new java.util.Date());
msg.setContent(multipart);
//send email
Transport.send(msg);
问题是我正在设置
os=response.getOutputStream
相反,我摆脱了这一行,创造了
byte[] outputBytes = os.toByteArray();
这就是我在dataSource中使用的内容。
什么是“ buf”? 为什么要将其转换为字符串,然后假设该字符串在iso-8859-1中进行编码,然后从该字符串中提取字节?
看起来PDF正在创建为“ os”,它没有保存在任何地方,也没有用于附件。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.