4
votes

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);
2
Check file is exit's in FileSystemResource using exists method - Rajesh
Please post the full exception stacktrace. - Mark Rotteveel

2 Answers

10
votes

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);
1
votes

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");