2016-10-20 114 views
0

我试图发送使用JavaMail的图像作为附件附件,而不必保存在文件系统中的实际图像。相反,我有一个Base64编码的字符串。发送图像与JAVAMAIL

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

我能收到一封电子邮件,罚款,但是当我做附件无法打开。

此外,当我使用getContentType()它显示text/plain而不是image/jpeg

回答

0

除非图像恰好是什么在文字部分的图像,你不希望它是相同的multipart /替代的一部分。相反,想要的外多部分/混合,其中第一部分是多部分/替代,并且其第二部分是图像/ JPEG。

如果图像的字符串已Base64编码,你会想要将它添加到多/混合时使用PreencodedMimeBodyPart。但它看起来像你第一次对其进行解码,然后将允许JavaMail来重新编码。这应该也可以,但效率较低。

如果你解决这一切,仍然没有得到的图像正确的内容类型,使用Message.writeTo将图像写入到一个FileOutputStream,然后在这里发表的输出。