首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >如何发送带附件的电子邮件

如何发送带附件的电子邮件
EN

Stack Overflow用户
提问于 2012-06-03 16:01:34
回答 1查看 2.5K关注 0票数 1

我想发一封附有图片的电子邮件。我用的是弹簧3和速度模板。我能够做到这一点,但由于某些原因,当我添加一个扩展与图像名称,我没有得到电子邮件传递。

下面是我所使用的代码:

代码语言:javascript
复制
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.com25作为端口。不过,我确实在控制台上成功地发送了电子邮件。但这封邮件从来没有发送过。

编辑:--如果我保持它像helper.addAttachment("formstack1", new ByteArrayResource(IOUtils.toByteArray(inputStream)));一样,并将扩展名从nothing更改为.jpg,同时下载附加的映像,我就会得到所需的映像。

有人能帮助我理解为什么会发生这种情况,以及如何使用spring 3发送带有一个或多个附件的电子邮件。

谢谢。

EN

回答 1

Stack Overflow用户

发布于 2012-06-03 16:23:33

您最好使用Apache通用HtmlEMail。

http://commons.apache.org/email/userguide.html

票数 2
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/10871804

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档