我正在使用Itext创建一个pdf,创建之后,我通过将其转换为byte []在邮件中发送它 我能够生成byte []并通过在线工具pdf检查,他们能够从我的byte []中生成pdf 但是当我从Java代码中发送此byte []时,文件已损坏。
下面是我的代码
这是我将pdf转换为字节的一半[]
document.close();
byte[] bytes = baos.toByteArray();
bytes = Base64.getEncoder().encode(bytes);
System.out.println(new String(bytes));
System.out.println("Done");
sendEmail(bytes);
从这里我要发送邮件
public static void sendEmail(byte[] pdf) throws IOException {
System.out.println("Starte");
System.out.println(new String(pdf));
final String username = "b*****@gmail.com";
final String password = "*****";
Properties prop = new Properties();
prop.put("mail.smtp.host", "smtp.gmail.com");
prop.put("mail.smtp.port", "465");
prop.put("mail.smtp.auth", "true");
prop.put("mail.smtp.socketFactory.port", "465");
prop.put("mail.smtp.socketFactory.class", "javax.net.ssl.SSLSocketFactory");
Session session = Session.getInstance(prop,
new javax.mail.Authenticator() {
protected PasswordAuthentication getPasswordAuthentication() {
return new PasswordAuthentication(username, password);
}
});
try {
Message message = new MimeMessage(session);
message.setFrom(new InternetAddress("*****@gmail.com"));
message.setRecipients(
Message.RecipientType.TO,
InternetAddress.parse("******@gmail.com, *****@gmail.com")
);
message.setSubject("Testing Gmail SSL");
message.setText("Dear Mail Crawler,"
+ "\n\n Please do not spam my email!");
Multipart multipart = new MimeMultipart(); //1
// Create the attachment part
BodyPart attachmentBodyPart = new MimeBodyPart(); //2
attachmentBodyPart.setDataHandler(new DataHandler(new ByteArrayDataSource(pdf,"application/pdf"))); //2
attachmentBodyPart.setFileName("Hello.pdf"); // 2
multipart.addBodyPart(attachmentBodyPart); //3
// Create the HTML Part
BodyPart htmlBodyPart = new MimeBodyPart(); //4
htmlBodyPart.setContent("Dear Mail Crawler,"
+ "\n\n Please do not spam my email!" , "text/html"); //5
multipart.addBodyPart(htmlBodyPart); // 6
// Set the Multipart's to be the email's content
message.setContent(multipart); //7
Transport.send(message);
System.out.println("Done");
} catch (MessagingException e) {
e.printStackTrace();
}
}
请让我知道代码有什么问题 任何帮助都将得到