使用 Java Mail API 保存电子邮件(包括图像和 HTML 数据)的最佳方法?

GSG*_*GSG 6 java pdf email jakarta-mail html-email

我正在寻找保存包含内嵌图像和 HTML 内容的电子邮件正文的最佳方法。我想保留邮件中包含的所有内容。

我的最终目标是将完整的电子邮件正文保存为 PDF

如果有直接的方法将电子邮件正文写入 PDF ?

如果不是,保存电子邮件的最佳格式是什么?

我可以使用其他一些可用的 API 将 HTML、DOC 等转换为 PDF。

private void downloadAttachment(Part part, String folderPath) throws Exception {
    String disPosition = part.getDisposition();
    String fileName = part.getFileName();
    String decodedText = null;
    logger.info("Disposition type :: " + disPosition);
    logger.info("Attached File Name :: " + fileName);

    if (disPosition != null && disPosition.equalsIgnoreCase(Part.ATTACHMENT)) {
        logger.info("DisPosition is ATTACHMENT type.");
        File file = new File(folderPath + File.separator + decodedText);
        file.getParentFile().mkdirs();
        saveEmailAttachment(file, part);
    } else if (fileName != null && disPosition == null) {
        logger.info("DisPosition is Null type but file name is valid.  Possibly inline attchment");
        File file = new File(folderPath + File.separator + decodedText);
        file.getParentFile().mkdirs();
        saveEmailAttachment(file, part);
    } else if (fileName == null && disPosition == null) {
        logger.info("DisPosition is Null type but file name is null. It is email body.");
        File file = new File(folderPath + File.separator + "mail.html");
        file.getParentFile().mkdirs();
        saveEmailAttachment(file, part);
    }


}
     protected int saveEmailAttachment(File saveFile, Part part) throws Exception {

    BufferedOutputStream bos = null;
    InputStream is = null;
    int ret = 0, count = 0;
    try {
        bos = new BufferedOutputStream(new FileOutputStream(saveFile));
        part.writeTo(new FileOutputStream(saveFile));

    } finally {
        try {
            if (bos != null) {
                bos.close();
            }
            if (is != null) {
                is.close();
            }
        } catch (IOException ioe) {
            logger.error("Error while closing the stream.", ioe);
        }
    }
    return count;
} 
Run Code Online (Sandbox Code Playgroud)

请建议。谢谢!

Wil*_*ung 5

将其保存为自然状态,作为 MimeMessage。

JavaMail MimeMessages 可以流式传输为文本,因为这就是它们通过邮件到达的方式。例如,MimeMessage.writeTo将消息保存为文本。类似地,MimeMessage.parse将其读回。在 MimeMessage 中的一个,您可以很容易地获取文本、附件等。

您也可以将其作为序列化的 Java 对象进行流式处理,但坦率地说,我不会。文本表示更有用。