我想發送一封帶有附件的電子郵件:
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("[email protected]"));
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
uj5u.com熱心網友回復:
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("[email protected]"));
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());
}
}
uj5u.com熱心網友回復:
我會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("[email protected]"));
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());
}
}
轉載請註明出處,本文鏈接:https://www.uj5u.com/qukuanlian/413556.html
標籤:
