【问题标题】:downloading email body containing inline images in java在java中下载包含内联图像的电子邮件正文
【发布时间】:2012-11-10 13:40:10
【问题描述】:

我的问题如下:

我设置了我的代码来阅读来自特定帐户的电子邮件。这部分工作得很好。

问题在于解析电子邮件。分离附件和电子邮件正文(包含内嵌图像)。

我的代码是这样的:

    Void readMessages(Folder folder){

          Message[] messages = folder.getMessages();
            // loading of message objects.
                for (int messageNumber = 0; messageNumber < messages.length; messageNumber++) {

             final Message currentMessage = messages[messageNumber];
                 logger.info("Handling the mail with subject " + currentMessage.getSubject());
                logger.info("Content type for the current message is " +                                  currentMessage.getContentType());
                final String messageFileName = currentMessage.getFileName();
                logger.info("File name for the message " + messageFileName + ". File name is blank "
                                                +                     StringUtils.isBlank(messageFileName));


                        Object messageContentObject = currentMessage.getContent();
                        if (messageContentObject instanceof Multipart) {
                            Multipart multipart = (Multipart) messageContentObject;

                            // downloading all attachments....
                            int attachmentCount = multipart.getCount();
                            logger.info("Number of attachments ");
                            for (int i = 0; i < attachmentCount; i++) {
                                Part part = (Part) multipart.getBodyPart(i);
                                downloadAttachment(part, folderPath.toString());
                            }

                        }

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

我遇到的问题是,当我运行此代码时,我得到了一个 HTML 文件,但内联图像被错误图像的符号替换,表示该图像没有来源。

请帮帮我。如果需要更多信息,请告诉我。

我还尝试通过更改将正文保存为.eml 文件:

 File file = new File(folderPath + File.separator + "mail.html"); 

 File file = new File(folderPath + File.separator + "mail.eml");

但是我得到了相同的结果。

【问题讨论】:

  • "..通过错误图像的符号表示图像没有来源。"你确定源是空的吗?你检查过 HTML 源代码吗?
  • 检查这个 HTML 文件。 dropbox.com/s/5evk4pjq721yo8m/mail.html
  • 此 HTML 将向您显示缺少的图像源。
  • 来源没有丢失。它只是不是硬盘驱动器或网络上的位置。它是对多部分消息中另一部分的引用。
  • 浏览器有没有办法渲染这样的东西?浏览器可以从 HTML 中读取源代码吗?如果我的内容流存在于 HTML 中。如果是,需要什么标签来识别它?

标签: java email inline-images


【解决方案1】:

对内联图像的引用被 cid: URN 替换,例如 &lt;img src="cid:SOMEID"&gt;,因为电子邮件中没有文件名。 SOMEID 是指多部分“对象”的 Content-ID。

为了让它工作,您必须将多部分附件存储到文件中(例如,临时名称)并用真实文件名替换 cid URN。

【讨论】:

  • 当然!我会试试这个。
  • 这怎么可能我也有同样的问题。我已成功下载内联图像,但无法使用我的原始路径回复 src:cid 请尽可能尽快给我解决方案。
  • 对我也不起作用。仍在寻找出路。
【解决方案2】:

我在下面编写了将电子邮件正文文本转换为 pdf 的代码,包括内联图像。 在代码中,我用下载图像路径替换了图像代码(例如:cid:image001.jpg@01D17AAA.1EA2A6A0)。下载图像时,我正在为图像密钥和下载路径构建“哈希图”。

 HTMLWorker htmlWorker = new HTMLWorker(document);
            if(bodyStr!=null)
            {

                //find inline images
                inlineImages=downloadInLineImage(mostRecentMatch, dynamicOutputDirectory);
                if(inlineImages!=null)
                {

                    for (Map.Entry<String, String> entry : inlineImages.entrySet()) {
                        //System.out.println("Key = " + entry.getKey() + ", Value = " + entry.getValue());
                        bodyStr=bodyStr.replaceAll("cid:"+entry.getKey() , entry.getValue());
                    }
                }
                htmlWorker.parse(new StringReader(bodyStr));

        }

下载带有传递项的内联图像。

 private HashMap<String,String> downloadInLineImage(Item item, String dynamicOutputDirectory)
        throws Exception, ServiceLocalException {
    //create output directory if not present

        //bind the item to a new email message. if you do not bind, then the getHasAttachments() function will fail
    EmailMessage mostRecentMatch = (EmailMessage)item;
    String from = mostRecentMatch.getFrom().getAddress();
    String user =StringUtils.substringBefore(from, "@");
    AttachmentCollection collection=item.getAttachments();

    HashMap<String,String> inlineFiles=new HashMap<String,String>();

    if(collection.getCount()>0)
    {
        for (Attachment attachment : collection.getItems()) {

            if(attachment.getIsInline())
            {

                FileAttachment currentFile = (FileAttachment) attachment;
                String filePath=dynamicOutputDirectory+"/"+user+currentFile.getName();
                File file=new File(filePath);
                FileOutputStream fio=new FileOutputStream(file);
                currentFile.load(fio);
                inlineFiles.put(currentFile.getContentId(), filePath);
                fio.close();
            }
        }
    }

【讨论】:

    猜你喜欢
    • 2016-07-10
    • 2018-05-05
    • 2020-10-20
    • 2013-11-18
    • 2020-02-08
    • 2017-06-26
    • 2010-11-20
    • 1970-01-01
    • 2014-09-01
    相关资源
    最近更新 更多