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

标签 java email pdf jakarta-mail html-email

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

My ultimate Goal is to save the complete email body into a 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;
} 

请推荐。谢谢!

最佳答案

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

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

您也可以将其作为序列化的 Java 对象流式传输,但坦率地说,我不会这样做。文本表示更有用。

关于java - 使用 Java Mail API 保存电子邮件(包括图像和 HTML 数据)的最佳方式?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13577389/

相关文章:

java - 日历序列化反序列化

forms - 如何在 Outlook 的新邮件表单之间插入自定义字段?

pdf - 如何将注释/突出显示从一个 PDF 复制到该 PDF 的更新版本?

使用电子邮件地址之谜的 PHP/MySQL SELECT 查询

c# - iTextSharp - 在电子邮件附件中发送内存中的 pdf

java - 使 JFreeChart CategoryPlot 看起来像 Flot.js 条形图

ios - 通过 UIDocumentInteractionController 允许 PDF 的预览选项

java - 缺少 Eclipse 4 RCP 部署应用程序 XMI 参数

java - 如何用Configuration配置Hibernate+JPA?

java - java中的合并排序和复制数组,仍然是nlogn?