[英]java.io.IOException: Exception writing Multipart with SpringBoot
我想發送一個帶有附件的 email:
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
object 並使用它來定義正文和附加文件。
你應該這樣做:
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());
}
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.