【问题标题】:How to send email with attachments如何发送带附件的电子邮件
【发布时间】: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.com25 作为端口。不过,我确实在控制台上收到了成功发送电子邮件的消息。但是邮件 永远不会交付。

编辑:如果我保持它像 helper.addAttachment("formstack1", new ByteArrayResource(IOUtils.toByteArray(inputStream))); 一样,并在下载附加图像时将扩展名从无更改为 .jpg,我确实得到了所需的图像。

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

谢谢。

【问题讨论】:

    标签: spring email email-attachments


    【解决方案1】:

    你最好使用 Apache Commons HtmlEMail

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

    【讨论】:

    • 无法获得commons-email-1.3 版本,并且maven 存储库只有commons-email-1.1 最新版本。我错过了什么吗? apache.techartifact.com/mirror//commons/email/binaries/… 是那个的下载链接。
    • 看起来 .jpg 图像不符合规范,即使在将内容类型设置为 image/jpeg 后它也不起作用。但是当我尝试.png 时,一切正常。
    猜你喜欢
    • 2015-08-28
    • 2014-04-23
    • 2019-03-09
    • 2015-09-09
    • 1970-01-01
    相关资源
    最近更新 更多