java邮件Base64编码字符串到图像附件

Coe*_*men 3 java jakarta-mail

我有一个base64编码的字符串,使用JSON发布到Spring表单中.

data:image/png;base64,iVBORw0KGg......etc
Run Code Online (Sandbox Code Playgroud)

我想将此图像添加为电子邮件的附件.附加文件工作正常,但它只是添加base64字符串作为附件.

我使用以下代码来创建附件部分.

private MimeBodyPart addAttachment(final String fileName, final String fileContent) throws MessagingException {

    if (fileName == null || fileContent == null) {
        return null;
    }

    LOG.debug("addAttachment()");

    MimeBodyPart filePart = new MimeBodyPart();

    String data = fileContent;
    DataSource ds;
    ds = new ByteArrayDataSource(data.getBytes(), "image/*");

    // "image/*"
    filePart.setDataHandler(new DataHandler(ds));
    filePart.setFileName(fileName);

    LOG.debug("addAttachment success !");

    return filePart;

}
Run Code Online (Sandbox Code Playgroud)

我也试过了

 ds = new ByteArrayDataSource(data, "image/*");
Run Code Online (Sandbox Code Playgroud)

如何使用ByteArrayDataSource将base64字符串转换为正确的图像文件?

jme*_*ens 7

要避免解码和重新编码,可以使用javax.mail.internet.PreencodedMimeBodyPart加载base64字符串并将PreencodedMimeBodyPart附加到邮件中.

    private MimeBodyPart addAttachment(final String fileName, final String fileContent) throws MessagingException {
        if (fileName == null || fileContent == null) {
            return null;
        }

        LOG.debug("addAttachment()");
        MimeBodyPart filePart = new PreencodedMimeBodyPart("base64");
        filePart.setContent(fileContent, "image/*");
        LOG.debug("addAttachment success !");
        return filePart;
    }
Run Code Online (Sandbox Code Playgroud)

否则,您可以使用javax.mail.internet.MimeUtility :: decode来包装与数据源一起使用的输入流,但这将解码并重新编码给定数据.

    private MimeBodyPart addAttachment(final String fileName, final String fileContent) throws MessagingException {
        if (fileName == null || fileContent == null) {
            return null;
        }

        LOG.debug("addAttachment()");
        MimeBodyPart filePart = new MimeBodyPart();

        String data = fileContent;
        DataSource ds;  //Assuming fileContent was encoded as UTF-8.
        InputStream in = new ByteArrayInputStream(data.getBytes("UTF-8"));
        try {
            in = MimeUtility.decode(in, "base64");
            try {
                ds = new ByteArrayDataSource(in , "image/*");
            } finally {
                in.close();
            }
        } catch (IOException ioe) {
            throw new MessagingException(fileName, ioe);
        }

        // "image/*"
        filePart.setDataHandler(new DataHandler(ds));
        filePart.setFileName(fileName);

        LOG.debug("addAttachment success !");
        return filePart;
    }
Run Code Online (Sandbox Code Playgroud)


pie*_*t.t 6

你将首先使用Base64解码器.使用Java 8,您可以:

byte[] imgBytes = Base64.getDecoder().decode(base64String);
Run Code Online (Sandbox Code Playgroud)

对于较旧的java版本,你将不得不使用一些像apache commons-codec这样的库 - 其中有很多这样的库.