Spring Email Mime Base64图像

时间:2017-08-27 19:42:58

标签: java spring email spring-boot base64

我有一个java / spring启动应用程序,我希望能够从中发送电子邮件。电子邮件本身只是一堆文本,然后在底部有一个图像。我收到了发送所有正确文字的电子邮件,但图片从未出现过。这是我的代码:

MimeMessage message = mailSender.createMimeMessage();
MimeMessageHelper helper = new MimeMessageHelper(message, MULTIPART_MODE_RELATED);
helper.setFrom("test@gmail.com");
helper.setTo("testreceiver@gmail.com");
helper.setSubject("This is a test email from my app");

// This mail has 2 part, the BODY and the embedded image
MimeMultipart root = helper.getRootMimeMultipart();

// first part (the html)
BodyPart textPart = new MimeBodyPart();
textPart.setContent("Some cool html <bold>text</bold>", "text/html");
root.addBodyPart(textPart);

// second part (the image)
BodyPart imagePart = new PreencodedMimeBodyPart( "base64" );
imagePart.setHeader( "Content-ID", "<image>" );
imagePart.setDisposition( MimeBodyPart.INLINE );
imagePart.setText("iVBORw0KGgoAAAANSUhEUgAAAIAAAACACAYAAADDPmHLAAAABHNCSVQICAgIfAhkiAAAAAlwSFlzAAADdgAAA3YBfdWCzAAAABl0RVh0U29mdHdhcmUAd3d3Lmlua3NjYXBlLm9yZ5vuPBoAAAz9SURBVHja7Z17UFTXHcfVmtSaJuMkTjvOdJpJTTpXo/iKim8EdmFf+EhMrK22Wq1mJs201SbqxBTbtE2aNvJY3kRINUqMqVExPgGRpwq4+ChxrA8kgiCCL14inP7OsmsW5O7uvffce+69nD8+/yC7Muf7Pef8fr/z6ocQ6qdW4oqMK2OPGcoSC4xT1fx39kZqmfnZpHLLpuQzFlX/7apuxMicyIHROcEPoo4Eo5jc0Mq4IsMv1C58ymnLhORyy3agPancfDUSRQ5gBpBAbJ4hDxvATUxuSCP8LBL+SUUN269/0imLJfm0JQeERw9xWP+i9vZVvQHiC8NmeRrATXROSKs935geU2x6itbfFnPB9N2UcsuvQfhz3YTvonPzactPmAFINDT0+t5M4CQrpMOeZzwUVxg2XLH5/VzY0yD8eqCmF+G7gNFAC22rCQPE5RsS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aADAVDICsoJYdIqFOJtBfcQO4TPACzaNkbCrgqoBnpGgoyQCueGAVzQJRH14swvP+NKn6STaAq0qYQjMe6IO7iPEp31+S0I6IAdRw1XwfWzBaQ0o3YgZwbSE7TvPFsT6SGfyDpGZEDeC6cfwCzWdndb6bOI20XsQNAJnBIJpnCvDDEzo1wRZgoOoN4K4RwHRQSrNc3Kov8T+SkusrbgCPwPAAzZFAJ3sI1sqpkawGcKWIm2lmBxquEzwAlsmtj+wGcJngbZqnjDR42LQWMCihjSIGcFUMx8Kw3Ehz7UAjwWEOMEwpXRQzgPtpWhAil2aaqOKCEb7CZWNbj6dddWUAj9FgNa1FJFw6vqO+CymvAsE0tKBiAPclFJCuFdFMFVVwI9l94H2+yxt0bQCP0cBC+7UySiXkbGAE7fanbgCPTMEO00I7rWkBRiSlgsQrwCK1tLtqDODecApG+BiCtTZadQMZt56fB5aK2bjZZwzgmS2AEWJoPWOHswUcKBIqJ58GFiod3WvaAJ5rCmCE9XVm7ko1pakBxwgiqolNwDYgTK4afp8wQA8zDAMxUmkFjHh6wI9beqkj4Dw+C/gV8KRW2lUzBuiROUyst3JbYWSopFFixjeX4PIyZA83QOwMYCXwIy22pSYN0Ish5oIhPseHV2tM3H25NqCC8K03LNwlGIm2A6/Czx/XetvpwgC9TBdDwBTz8SNY9RYuC4xxGaaOevw0Lg4scboJ83unW1g8isDP78PvNMHvNoDI1+BzXwPZYCw7/i4ICr+vx7b6P/RV5o7Zs+AIAAAAAElFTkSuQmCC");
root.addBodyPart(imagePart);

message.setContent(root);
mailSender.send(message);

我做错了什么?

1 个答案:

答案 0 :(得分:1)

您可以使用以下代码生成base64图像字符串并附加电子邮件:

Path path = Paths.get("IMAGE_LOCATION");
byte[] bytes = Files.readAllBytes(path);
Encoder encoder = Base64.getEncoder();
String base64String = encoder.encodeToString(bytes);
String base64Image = "data:image/png;base64," + base64String;
System.out.println(base64Image);

以上代码考虑了PNG image

的示例