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

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

data:image/png;base64,iVBORw0KGg......etc 

我想将此图像添加为电子邮件的附件。 附加文件工作正常,但它只是添加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; } 

我也试过了

  ds = new ByteArrayDataSource(data, "image/*"); 

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

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

 byte[] imgBytes = Base64.getDecoder().decode(base64String); 

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

要避免解码和重新编码,可以使用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.setText(fileContent); LOG.debug("addAttachment success !"); return filePart; } 

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

  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; } 

我遇到同样的问题,我能够使用此代码修复它:

//在使用decodeBase64(数据)之前,必须首先解析数据以删除“data:image / png; base64”。

 byte[] imgBytes = Base64.decodeBase64(data); ByteArrayDataSource dSource = new ByteArrayDataSource(imgBytes, "image/*");