我想发一封附有图片的电子邮件。我用的是弹簧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作为helper.addAttachment("formstack1", new ByteArrayResource(IOUtils.toByteArray(inputStream)));中要附加的资源的名称时,formstack1更改为formstack1.jpg时,我甚至没有收到发送的电子邮件。我使用smtp.gmail.com和25作为端口。不过,我确实在控制台上成功地发送了电子邮件。但这封邮件从来没有发送过。
编辑:--如果我保持它像helper.addAttachment("formstack1", new ByteArrayResource(IOUtils.toByteArray(inputStream)));一样,并将扩展名从nothing更改为.jpg,同时下载附加的映像,我就会得到所需的映像。
有人能帮助我理解为什么会发生这种情况,以及如何使用spring 3发送带有一个或多个附件的电子邮件。
谢谢。
发布于 2012-06-03 16:23:33
您最好使用Apache通用HtmlEMail。
http://commons.apache.org/email/userguide.html
https://stackoverflow.com/questions/10871804
复制相似问题