我想在向收件人发送电子邮件时包含附件。我已经能够设置和获取附件,但是当从 Javaxmail 调用 attachFile 方法时出现错误。
此代码是使用 javax 库用 Java 编写的。
一切似乎都很好,但失败了。我也尝试过添加编码,但结果相同。
当调用 attachFile 方法时,此代码失败。
attachPart.attachFile(f); // fails here...
try {
Message msg = new MimeMessage(propsSess);
msg.setFrom(new InternetAddress(this.defaultSenderAddress));
setRecipient(msg, this.sendTo, "to");
msg.setSubject(this.subject);
msg.setContent(this.bodyHtml, "text/html");
msg.setHeader("X-Mailer", "Java Agent");
msg.setSentDate(new Date());
if (!this.bodyAttach.isEmpty()) {
BodyPart messageText = new MimeBodyPart();
messageText.setText(this.bodyHtml);
Multipart multipart = new MimeMultipart();
multipart.addBodyPart(messageText);
// adds attachments
for (int index = 0; index < this.bodyAttach.size(); index++) {
MimeBodyPart attachPart = new MimeBodyPart();
try {
System.out.println(this.bodyAttach.get(index)); // shows only 1st attachments
File f = new File(this.bodyAttach.get(index));
attachPart.attachFile(f); // fails here...
} catch (IOException ex) {
ex.printStackTrace();
}
multipart.addBodyPart(attachPart);
}
// sets the multi-part as e-mail's content
msg.setContent(multipart);
}
SMTPTransport transport = (SMTPTransport) propsSess.getTransport("smtp");
transport.connect(this.smtpServerAddress, null, null);
if (transport.isConnected()) {
transport.sendMessage(msg, msg.getAllRecipients());
transport.close();
this.processMessage.add("success");
}
} catch (Exception e) {
this.processMessage.add(databaseTitle + ": SmtpMail bean: Message or SMTPTransport error");
return false;
}
HUH函数
相关分类