Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

JavaMailSender with Exception writing Multipart

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);
like image 504
lry Avatar asked Jan 31 '19 02:01

lry


2 Answers

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);
like image 53
lry Avatar answered Nov 11 '22 03:11

lry


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

like image 2
Ramesh Avatar answered Nov 11 '22 04:11

Ramesh