简体   繁体   English

使用Javamail将图像作为附件发送

[英]Sending an image as attachment with Javamail

I'm trying to send an image using Javamail as an attachment without having an actual image saved in the file system. 我正在尝试使用Javamail作为附件发送图像,而没有在文件系统中保存实际图像。 Instead I have a Base64 encoded string. 相反,我有一个Base64编码的字符串。

public void sendMultiPartMailWithAttachments(final String[] recipient, final String from,
        @Nullable final String replyTo, @Nullable final String replyToName, final String subject,
        final String plainText, final String html, String image)
        throws MessagingException, AddressException, UnsupportedEncodingException {
    Message msg = this.setupMessage(recipient, from, replyTo, replyToName, subject);

    // Create the text part
    MimeBodyPart textPart = new MimeBodyPart();
    textPart.setText(plainText, "utf-8");

    MimeBodyPart htmlPart = new MimeBodyPart();
    htmlPart.setContent(html, "text/html; charset=utf-8");

    byte[] bytes = Base64.getMimeDecoder().decode(image);
    MimeBodyPart imagePart = new MimeBodyPart();
    // imagePart.setDataHandler(new DataHandler(imageObject, "image/jpeg"));
    imagePart.setDataHandler(new DataHandler(new ByteArrayDataSource(bytes, MediaType.JPEG.toString())));
    imagePart.setFileName("proof_test.jpg");

    Multipart multiPart = new MimeMultipart("alternative");
    multiPart.addBodyPart(textPart);
    multiPart.addBodyPart(htmlPart);
    multiPart.addBodyPart(imagePart);

    msg.setContent(multiPart);

    msg.saveChanges();

    Transport.send(msg);
}

I'm able to receive an email fine but when I do the attachment is unable to be opened. 我可以很好的接收电子邮件,但是当我打开附件时无法打开。

Also, when I use getContentType() it displays text/plain as opposed to image/jpeg . 另外,当我使用getContentType()它会显示text/plain而不是image/jpeg

Unless the image is exactly an image of what's in the text part, you don't want it to be part of the same multipart/alternative. 除非图像完全是文本部分中的图像,否则您不希望它成为同一多部分/替代项的一部分。 Instead, you want an outer multipart/mixed, the first part of which is the multipart/alternative, and the second part of which is the image/jpeg. 相反,您需要一个外部multipart / mixed,其第一部分是multipart / alternative,而第二部分是image / jpeg。

If the image string is already base64 encoded, you'll want to use a PreencodedMimeBodyPart when adding it to the multipart/mixed. 如果图像字符串已经通过base64编码, 在将其添加到multipart / mixed中时,需要使用PreencodedMimeBodyPart But it looks like you're decoding it first, which will then allow JavaMail to re-encode it. 但看起来您首先要对其进行解码,然后它将允许JavaMail重新对其进行编码。 That should work as well, but is less efficient. 那应该也可以,但是效率较低。

If you fix all this and still don't get the correct content type for the image, use Message.writeTo to write the image to a FileOutputStream, and then post the output here. 如果解决了所有这些问题,但仍然没有获得图像的正确内容类型,请使用Message.writeTo将图像写入FileOutputStream,然后将输出发布到此处。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM