I want to include attachments when email is sent to a recipient. I have been able to set and get the attachments but when the attachFile method is called from the Javaxmail I get an error.
This code is written in Java using the javax library.
Everything seems fine, but fails. I've tried adding encoding as well but same results.
This code fails when the attachFile method is called.
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;
}