Reputation: 299
When I used JavaMailSender to send e-mail with attachment, It always failed and throw the exception below:
org.springframework.mail.MailSendException: Failed messages: javax.mail.MessagingException: IOException while sending message;
nested exception is:
java.io.IOException: Exception writing Multipart
; message exception details (1) are:
Failed message 1:
javax.mail.MessagingException: IOException while sending message;
nested exception is:
java.io.IOException: Exception writing Multipart
at com.sun.mail.smtp.SMTPTransport.sendMessage(SMTPTransport.java:1365)
at org.springframework.mail.javamail.JavaMailSenderImpl.doSend(JavaMailSenderImpl.java:462)
at org.springframework.mail.javamail.JavaMailSenderImpl.send(JavaMailSenderImpl.java:359)
at org.springframework.mail.javamail.JavaMailSenderImpl.send(JavaMailSenderImpl.java:354)
Here is my code
MimeMessage message = mailSender.createMimeMessage();
try {
MimeMessageHelper helper = new MimeMessageHelper(message, true);
helper.setFrom(userName);
helper.setTo(toAddress);
helper.setSubject(subject);
FileSystemResource file = new FileSystemResource(filePath);
helper.addAttachment(file.getFilename(), file);
} catch (Exception e) {
log.error("oops..., ", e);
}
mailSender.send(message);
Upvotes: 8
Views: 10576
Reputation: 341
It gives this error if you don't set the text. You need to set text even if you set it to an empty string.
https://stackoverflow.com/a/33015901/9905202
Upvotes: 1
Reputation: 89
set content type, I resoled this by setting content type as 3rd parameter
helper.addAttachment("Attachment File name", new ByteArrayResource(IOUtils.toByteArray(inputStream)), "application/pdf");
Upvotes: 2
Reputation: 299
em, I've solved this problem by luck.
Just set an empty text content with your attachment, like this and it works.
helper.addAttachment(MimeUtility.encodeText("")), new ByteArrayResource(IOUtils.toByteArray(inputStream)));
helper.setText("", true);
Upvotes: 18