如何在电子邮件中附加图片?我正在使用AWS SES服务通过JAVA发送电子邮件-Spring Boot [英] How do i attach image in email? I am using AWS SES Service to send email using JAVA - Spring Boot

查看:177
本文介绍了如何在电子邮件中附加图片?我正在使用AWS SES服务通过JAVA发送电子邮件-Spring Boot的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在AWS上托管了一个Spring Boot应用程序.我正在使用AWS SES触发电子邮件.但是我不知道如何使用SES附加图像.我正在使用JAVA作为应用程序源代码.数据存储在数据库中,但未发送电子邮件.

I have a Spring Boot application hosted on AWS. I am using AWS SES to trigger email. But i am lost as to how to attach an image using SES. I am using JAVA as application source code.The data are stored in the database but the email is not sent.:


   public void sendEmail(String to, String subject, String body) throws MessagingException {
        Properties props = System.getProperties();
        props.put("mail.transport.protocol", "smtp");
        props.put("mail.smtp.port", PORT);
        props.put("mail.smtp.starttls.enable", "true");
        props.put("mail.smtp.auth", "true");

        Session session = Session.getDefaultInstance(props);

        Message msg = new MimeMessage(session);
        MimeMultipart multipart = new MimeMultipart();
        BodyPart messageBodyPart = new MimeBodyPart();
        // the body content:
        messageBodyPart.setContent(BODY, "text/html");
        multipart.addBodyPart(messageBodyPart);
        // the image:
        messageBodyPart = new MimeBodyPart();
        DataSource fds = new FileDataSource(
                "Logo.png");
        messageBodyPart.setDataHandler(new DataHandler(fds));
        messageBodyPart.setHeader("Content-ID", "<image_01>");
        multipart.addBodyPart(messageBodyPart);
        // add the multipart to the message:
        msg.setContent(multipart);
        // set the remaining values as usual:
        try {
            msg.setFrom(new InternetAddress(FROM, FROMNAME));
        } catch (UnsupportedEncodingException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } catch (MessagingException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        msg.setRecipient(Message.RecipientType.TO, new InternetAddress(to));
        msg.setSubject(SUBJECT);

        Transport transport = session.getTransport();

        try {
            System.out.println("Sending...");
            transport.connect(HOST, SMTP_USERNAME, SMTP_PASSWORD);
            transport.sendMessage(msg, msg.getAllRecipients());
            System.out.println("Email sent!");
        } catch (Exception ex) {
            System.out.println("The email was not sent.");
            ex.printStackTrace();
        } finally {
            transport.close();
        }
    }

project_structure 推荐答案

要将图像嵌入到电子邮件中,您需要对代码进行一些更改.我使用SES帐户,JavaMail和gmail网络客户端测试了这些更改:

To embed an image into your e-mail, you need to make a couple of changes to your code. I tested these changes using an SES account, JavaMail and a gmail web client:

使用Content ID方案( cid:)

Use the Content ID Scheme (cid:)

以下是使用 cid 的身体内容:

Here is your body content using a cid:

static final String BODY = String.join(System.getProperty("line.separator"),
    "<html><head></head><body><img src=\"cid:image_01\"></html> <br>"
    + "Welcome to ABC and have a great experience.");

在此示例中, image_01 是我要使用的任何标识符.显示邮件时, cid:方案表示电子邮件客户端将在邮件中查找 Content-ID 标头,并使用该名称检索相关图像-但是名称必须用尖括号< > 括起来才能内嵌显示(见下文).

In this example, image_01 is whatever identifier I want to use. When the mail is displayed, the cid: scheme means that the email client will look for a Content-ID header in the message, and retrieve the related image using that name - but the name will need to be enclosed in angle brackets < and > to be displayed inline (see below).

此处查看更多信息.

创建多部分Mime消息

您的 MimeMessage msg 对象将需要以不同的方式构建:

Your MimeMessage msg object will need to be built differently:

Message msg = new MimeMessage(session);
MimeMultipart multipart = new MimeMultipart();
try {
    BodyPart messageBodyPart = new MimeBodyPart();
    // the body content:
    messageBodyPart.setContent(BODY, "text/html");
    multipart.addBodyPart(messageBodyPart);
    // the image:
    messageBodyPart = new MimeBodyPart();
    DataSource fds = new FileDataSource("/your/path/to/logo.png");
    messageBodyPart.setDataHandler(new DataHandler(fds));
    messageBodyPart.setHeader("Content-ID", "<image_01>");
    multipart.addBodyPart(messageBodyPart);
    // add the multipart to the message:
    msg.setContent(multipart);
    // set the remaining values as usual:
    msg.setFrom(new InternetAddress(FROM, FROMNAME));
    msg.setRecipient(Message.RecipientType.TO, new InternetAddress(to));
    msg.setSubject(SUBJECT);
} catch (UnsupportedEncodingException | MessagingException ex) {
    Logger.getLogger(App.class.getName()).log(Level.SEVERE, null, ex);
}

在这里,我们构建一条由两部分组成的消息:

Here we build a message consisting of two parts:

  1. 来自 BODY 的HTML内容.
  2. 图片.

在我的示例中,映像是文件系统上的文件-但您可以以应用程序所需的任何方式(例如,通过资源)访问它.

In my example, the image is a file on the filesystem - but you can access it in whatever way you need for your application (e.g. via a resource).

请注意在设置标题时使用尖括号(如前所述):

Note the use of angle brackets when setting the header (as mentioned earlier):

messageBodyPart.setHeader("Content-ID", "<image_01>");

现在,您可以按照通常的方式发送邮件了:

Now you can send the message in the usual way:

try ( Transport transport = session.getTransport()) {
    System.out.println("Sending...");
    transport.connect(HOST, SMTP_USERNAME, SMTP_PASSWORD);
    transport.sendMessage(msg, msg.getAllRecipients());
    System.out.println("Email sent!");
} catch (Exception ex) {
    Logger.getLogger(App.class.getName()).log(Level.SEVERE, null, ex);
}

关于 JavaMailSender

A Note on JavaMailSender

在您的代码中,包括以下内容:

In your code, you include this:

private JavaMailSender mailSender;

是Spring围绕JavaMail(现在为JakartaMail)对象的包装.您无需在代码中使用此对象.

which is Spring's wrapper around the JavaMail (now JakartaMail) object. You don't make use of this object in your code.

鉴于您正在使用Spring,我建议您使用上述方法,然后重构代码以使用Spring的邮件助手实用程序.有很多其他的指南和教程.

Given you are using Spring, I would recommend you get the above approach working, and then refactor your code to make use of Spring's mail helper utilities. There are lots of guides and tutorials for that elsewere.

关于SES的说明

上述方法使用的是Amazon的 SESSMTP接口.换句话说,您的代码中不需要任何Amazon SDK类.

The above approach is using Amazon's SES SMTP interface. In other words, no need for any Amazon SDK classes in your code.

这是我在测试此答案中的代码时使用的(使用SES帐户).

This is what I used when testing the code in this answer (using an SES account).

您当然可以考虑使用记录在此处

You can certainly look into using either of the other two approaches documented here and here - but neither is required for images to be displayed.

更新

有人问了一个有关此的澄清问题:

A question was asked, for clarification, about this:

messageBodyPart.setHeader("Content-ID", "<image_01>");

文本< image_01> 是您在HTML代码中引用图像的方式.因此,这就是我的示例代码使用此代码的原因:

The text <image_01> is how you refer to your image, in your HTML code. So, that is why my example code uses this:

<img src=\"cid:image_01\">

您可以在此处使用所需的任何标识符.在我的情况下,标识符"image_01"是指我的图像文件"logo.png".

You can use any identifier you want here. In my case the identifier "image_01" refers to my image file "logo.png".

但是要清楚一点-您确实需要在代码中包含< > .它们不仅仅像占位符"一样存在.在我的代码中-它们是您需要使用的语法的一部分.

But just to be clear - you really do need to include the < and the > in your code. They are not there just as "placeholders" in my code - they are part of the syntax you need to use.

但是请记住,如果您充分利用Spring和 Spring Mail Helper功能,则可以使一切变得更加简单.

But remember, you can make everything much simpler, if you take full advantage of Spring, and the Spring Mail Helper functions.

例如,这是相同的方法,使用Spring的 JavaMailSender MimeMessageHelper :

For example, here is the same approach, using Spring's JavaMailSender and MimeMessageHelper:

import java.io.UnsupportedEncodingException;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.activation.DataSource;
import javax.activation.FileDataSource;
import javax.mail.MessagingException;
import javax.mail.internet.MimeMessage;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.mail.javamail.JavaMailSender;
import org.springframework.mail.javamail.MimeMessageHelper;
import org.springframework.stereotype.Component;

@Component
public class MySpringMailer {

    static final String FROM = "donotreply@myaddress.com";
    static final String FROMNAME = "My Name";
    static final String TO = "my.email@myaddress.com";
    static final String SUBJECT = "Welcome to ABC";
    static final String BODY = String.join(System.getProperty("line.separator"),
            "<html><head></head><body><img src=\"cid:image_01\"></html> <br>"
            + "Welcome to ABC and have a really great experience.");

    @Autowired
    private JavaMailSender javaMailSender;

    public void sendSpringEmailWithInlineImage() {
        MimeMessage msg = javaMailSender.createMimeMessage();
        try {
            MimeMessageHelper helper = new MimeMessageHelper(msg, true); // true = multipart
            helper.setFrom(FROM, FROMNAME);
            helper.setTo(TO);
            helper.setSubject(SUBJECT);
            helper.setText(BODY, true); // true = HTML
            DataSource res = new FileDataSource("c:/tmp/logo.png");
            helper.addInline("image_01", res);
        } catch (UnsupportedEncodingException | MessagingException ex) {
            Logger.getLogger(App.class.getName()).log(Level.SEVERE, null, ex);
        }
        javaMailSender.send(msg);
    }

}

例如,现在,我们可以使用以下内容为图像文件创建引用:

So, for example, now we can create a reference for our image file using this:

helper.addInline("image_01", res);

请注意,当我们在Java代码中定义名称时,Spring不需要在这里使用< > .春天在幕后为我们解决了这个问题.

Note that Spring does not need us to use < and > here, when we are defining the name in our Java code. Spring takes care of that for us, behind the scenes.

这篇关于如何在电子邮件中附加图片?我正在使用AWS SES服务通过JAVA发送电子邮件-Spring Boot的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆