java.io.IOException:用SpringBoot编写Multipart时出现异常



我想发送一封带有附件的电子邮件:

public void sendMailWithAttachment(String to, String subject, String body, String fileToAttach) {
MimeMessagePreparator preparator = mimeMessage -> {
mimeMessage.setRecipient(Message.RecipientType.TO, new InternetAddress(to));
mimeMessage.setFrom(new InternetAddress("admin@gmail.com"));
mimeMessage.setSubject(subject);
mimeMessage.setText(body);
FileSystemResource file = new FileSystemResource(new File(fileToAttach));
System.out.println(file.contentLength());
MimeMessageHelper helper = new MimeMessageHelper(mimeMessage, true);
helper.addAttachment("logo.jpg", file);
};
try {
javaMailSender.send(preparator);
}
catch (MailException ex) {
// simply log it and go on...
System.err.println(ex.getMessage());
}
}

但我有一个例外:

Failed messages: javax.mail.MessagingException: IOException while sending message;
nested exception is:
java.io.IOException: Exception writing Multipart

Spring文档中给出的示例与您的代码不匹配:它创建了一个MimeMessageHelper对象,并使用它来定义主体和附加文件。

你应该这样做:

public void sendMailWithAttachment(String to, String subject, String body, String fileToAttach) {
MimeMessagePreparator preparator = mimeMessage -> {
MimeMessageHelper message = new MimeMessageHelper(mimeMessage, true, "UTF-8");
message.setRecipient(Message.RecipientType.TO, new InternetAddress(to));
message.setFrom(new InternetAddress("admin@gmail.com"));
message.setSubject(subject);
message.setText(body);
FileSystemResource file = new FileSystemResource(new File(fileToAttach));
message.addAttachment("logo.jpg", file);
};
try {
javaMailSender.send(preparator);
}
catch (MailException ex) {
// simply log it and go on...
System.err.println(ex.getMessage());
}
}

我会以不同的方式创建MimeMessagePreparator,并使用Streams读取文件。

public void sendMailWithAttachment(String to, String subject, String body, String fileToAttach) {
MimeMessagePreparator preparator = mimeMessage -> {
FileInputStream inputStream = new FileInputStream(new File(fileToAttach));
MimeMessageHelper message = new MimeMessageHelper(mimeMessage, true, "UTF-8");
message.setRecipient(Message.RecipientType.TO, new InternetAddress(to));
message.setFrom(new InternetAddress("admin@gmail.com"));
message.setSubject(subject);
message.setText(body);            
message.addAttachment("logo.jpg", new ByteArrayResource(IOUtils.toByteArray(inputStream)));

};
try {
javaMailSender.send(preparator);
}
catch (MailException ex) {
// simply log it and go on...
System.err.println(ex.getMessage());
}
}

这可能有多种原因。对我来说,它并没有设置文本。在您的情况下,如果body String为null,您可能会遇到同样的问题。

下面的答案帮我弄明白了。https://stackoverflow.com/a/33015901/9905202

相关内容

  • 没有找到相关文章

最新更新