【发布时间】:2012-06-07 23:10:08
【问题描述】:
我想发送一封附有图片的电子邮件。我正在使用带有速度模板的 spring 3。我可以这样做,但由于某些原因,当我添加带有图像名称的扩展时,我没有收到电子邮件。
以下是我使用的代码:
private MimeMessage createEmail(Application application, String templatePath, String subject, String toEmail, String fromEmail, String fromName) {
MimeMessage mimeMsg = mailSender.createMimeMessage();
Map<String, Object> model = new HashMap<String, Object>();
model.put("application", application);
String text = VelocityEngineUtils.mergeTemplateIntoString(velocityEngine, templatePath, model);
text = text.replaceAll("\n", "<br>");
try {
MimeMessageHelper helper = new MimeMessageHelper(mimeMsg, true);
helper.setSubject(subject);
helper.setTo(toEmail);
if (fromName == null) {
helper.setFrom(fromEmail);
} else {
try {
helper.setFrom(fromEmail, fromName);
} catch (UnsupportedEncodingException e) {
helper.setFrom(fromEmail);
}
}
helper.setSentDate(application.getDateCreated());
helper.setText(text, true);
InputStream inputStream = servletContext.getResourceAsStream("images/formstack1.jpg");
helper.addAttachment("formstack1", new ByteArrayResource(IOUtils.toByteArray(inputStream)));
} catch (MessagingException e) {
throw new RuntimeException(e);
}
catch (IOException e) {
throw new RuntimeException(e);
}
return mimeMsg;
}
使用上面的代码,我可以添加 formstack1 作为附件,但它没有扩展名,所以我没有得到 formstack1.jpg 图像文件。但是,当我使用 formstack1.jpg 作为要附加在 helper.addAttachment("formstack1", new ByteArrayResource(IOUtils.toByteArray(inputStream))); 中的资源名称时,由于 formstack1 更改为 formstack1.jpg,我什至没有收到电子邮件。我使用smtp.gmail.com 和25 作为端口。不过,我确实在控制台上收到了成功发送电子邮件的消息。但是邮件
永远不会交付。
编辑:如果我保持它像 helper.addAttachment("formstack1", new ByteArrayResource(IOUtils.toByteArray(inputStream))); 一样,并在下载附加图像时将扩展名从无更改为 .jpg,我确实得到了所需的图像。
有人可以帮我理解为什么会发生这种情况,以及如何使用 spring 3 发送带有 1 个或多个附件的电子邮件。
谢谢。
【问题讨论】:
标签: spring email email-attachments