编程语言
首页 > 编程语言> > 使用Java Mail API保存电子邮件(包括图像和HTML数据)的最佳方法?

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

作者:互联网

我正在寻找保存包含内嵌图像和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,pdf,javamail,html-email,email
来源: https://codeday.me/bug/20190625/1287223.html