2015-06-09 39 views
2

我正在使用下一代码从我的邮箱帐户使用javamail API下载附件和正文文本,它工作得很好。但是,如果电子邮件上有嵌入式或嵌入式图像,则不会将图像下载为文本或附件文件。我是Java新手,一直在网上阅读,但没有找到易于理解的实施解决方案。任何workarround或代码来完成它?如何从电子邮件中获取内嵌图像?

这是我使用的代码:

public void processMessageBody(Message message) { 
    try { 
     Object content = message.getContent(); 
     // check for string 
     // then check for multipart 
     if (content instanceof String) { 
      System.out.println(content); 
     } else if (content instanceof Multipart) { 
      Multipart multiPart = (Multipart) content; 
      procesMultiPart(multiPart); 
     } else if (content instanceof InputStream) { 
      InputStream inStream = (InputStream) content; 
      int ch; 
      while ((ch = inStream.read()) != -1) { 
       System.out.write(ch); 
      } 

     } 

    } catch (IOException e) { 
     e.printStackTrace(); 
    } catch (MessagingException e) { 
     e.printStackTrace(); 
    } 
} 

public void procesMultiPart(Multipart content) { 

    try { 

     for (int i = 0; i < content.getCount(); i++) { 
      BodyPart bodyPart = content.getBodyPart(i); 
      Object o; 

      o = bodyPart.getContent(); 
      if (o instanceof String) { 
       System.out.println("Text = " + o); 
      } else if (null != bodyPart.getDisposition() 
        && bodyPart.getDisposition().equalsIgnoreCase(
          Part.ATTACHMENT)) { 
       String fileName = bodyPart.getFileName(); 
       System.out.println("fileName = " + fileName); 
       InputStream inStream = bodyPart.getInputStream(); 
       FileOutputStream outStream = new FileOutputStream(new File(
         downloadDirectory + fileName)); 
       byte[] tempBuffer = new byte[4096];// 4 KB 
       int numRead; 
       while ((numRead = inStream.read(tempBuffer)) != -1) { 
        outStream.write(tempBuffer); 
       } 
       inStream.close(); 
       outStream.close(); 
      } 
      // else? 

     } 
    } catch (IOException e) { 
     e.printStackTrace(); 
    } catch (MessagingException e) { 
     e.printStackTrace(); 
    } 

} 

我曾尝试添加下一个如果statment显示一条消息,如果它是一个内联的图像,但无幸运:

public void procesMultiPart(Multipart content) { 

     try { 

      for (int i = 0; i < content.getCount(); i++) { 
       BodyPart bodyPart = content.getBodyPart(i); 
       Object o; 

       o = bodyPart.getContent(); 
// NOT WORKING 
       if (o instanceof Image) { 
        System.out.println("procesMultiPart has Inline Images"); 
       } 
// 
else if (o instanceof String) { 
        System.out.println("Text = " + o); 
       } else if (null != bodyPart.getDisposition() 
         && bodyPart.getDisposition().equalsIgnoreCase(
           Part.ATTACHMENT)) { 
        String fileName = bodyPart.getFileName(); 
        System.out.println("fileName = " + fileName); 
        InputStream inStream = bodyPart.getInputStream(); 
        FileOutputStream outStream = new FileOutputStream(new File(
          downloadDirectory + fileName)); 
        byte[] tempBuffer = new byte[4096];// 4 KB 
        int numRead; 
        while ((numRead = inStream.read(tempBuffer)) != -1) { 
         outStream.write(tempBuffer); 
        } 
        inStream.close(); 
        outStream.close(); 
       } 
       // else? 

      } 
     } catch (IOException e) { 
      e.printStackTrace(); 
     } catch (MessagingException e) { 
      e.printStackTrace(); 
     } 

    } 
+0

检查:http://stackoverflow.com/questions/26173888/java-mail-polling-read-inline-or-embedded-images-smileys-from-the-mail –

+0

也可以尝试'F( bodyPart.getContentType()。contains(“image /”))''而不是'if(o instanceof Image)' –

+0

坦克@NitinDandriyal,我试过if(bodyPart.getContentType()。contains(“image /”)) )并已阅读您提供的链接,但无法工作。我实现了getAttachments然后链接http://stackoverflow.com/questions/26173888/java-mail-polling-read-inline-or-embedded-images-smileys-from-the-mail,但没有识别内联图片我在我的电子邮件。谢谢 – Marcos

回答

0

的下面的代码应该适合你......

private String getAttachments(Message message, HttpServletRequest request) throws MessagingException, IOException { 
String contentType = message.getContentType(); 
String attachFiles=""; 
if (contentType.contains("multipart")) { 
    // content may contain attachments 
    Multipart multiPart = (Multipart) message.getContent(); 
    int numberOfParts = multiPart.getCount(); 
    for (int partCount = 0; partCount < numberOfParts; partCount++) { 
     MimeBodyPart part = (MimeBodyPart) multiPart.getBodyPart(partCount); 
     String disposition =part.getDisposition(); 
     String file=part.getFileName(); 
     //External attachments 
     if (disposition != null && Part.ATTACHMENT.equalsIgnoreCase(disposition)) { 
      // this part is attachment 
      String fileName = new Date().getTime()+ "_"+ part.getFileName().replaceAll("[^a-zA-Z0-9\\._]+", "_"); //To make attachment name uniq we are adding current datatime before name. 
      attachFiles += fileName + ","; //concrete all attachment's name with comma separated.     
      part.saveFile(new File(request 
        .getSession() 
        .getServletContext() 
        .getRealPath(
          "/WEB-INF/attechments/" 
            + fileName))); //To save the attachment file at specific location. 
    //     LOG.info("\n\t Path :- " +request.getSession().getServletContext().getRealPath("/WEB-INF/attechments/" + fileName)); 
     } 
     //Inline Attachments 
     else if (disposition != null && Part.INLINE.equalsIgnoreCase(disposition)) { 
      // this part is attachment 
      String fileName = new Date().getTime()+ "_"+ part.getFileName().replaceAll("[^a-zA-Z0-9\\._]+", "_"); //To make attachment name uniq we are adding current datatime before name. 
      // attachFiles += fileName + ","; //concrete all attachment's name with comma separated.     
      part.saveFile(new File(request 
        .getSession() 
        .getServletContext() 
        .getRealPath(
          "/WEB-INF/attechments/" 
            + fileName))); //To save the attachment file at specific location. 
//     LOG.info("\n\t Path :- " +request.getSession().getServletContext().getRealPath("/WEB-INF/attechments/" + fileName)); 
     } 
     //Inline icons and smileys 
     else if(file != null && disposition==null) 
     { 
      String fileName = new Date().getTime()+ "_"+ part.getFileName().replaceAll("[^a-zA-Z0-9\\._]+", "_"); 
     // attachFiles += fileName + ","; //concrete all attachment's name with comma separated. 
      part.saveFile(new File(request 
        .getSession() 
        .getServletContext() 
        .getRealPath(
          "/WEB-INF/attechments/" 
            + fileName))); 

     } 
    } 
} 
if (attachFiles.length() > 1) { 
    attachFiles = attachFiles.substring(0, attachFiles.length() - 1); 
} 
return attachFiles; 
} 
+0

谢谢@Pavan,我之前试过代码,没有检测到我的内联附件,无论如何,我会再试一次。 – Marcos

0

嵌入式图像将成为多部分/相关内容的一部分, t被标记为附件。有关这种消息的结构,请参阅RFC 2387

+0

但你知道如何从电子邮件下载它吗? – Marcos

+0

这是一个BodyPart,包含在Multipart中。 getContent方法不会返回一个Image对象,虽然它可能很好,如果它。使用bodyPart.isMimeType(“image/*”)来确定它是否为图像,然后使用((MimeBodyPart)bodyPart).saveFile(fileName)将其保存到文件中。 (在使用之前,请确保fileName是“安全的”。)即使如此,mutlipart/related中的html内容将需要修改,以使用适当的文件或http:URL引用保存的图像,而不是用于引用包含图像的cid:URL。 –

0
public static List<String> getAttachmentFileName(MimeMultipart mimeMultipart) throws Exception{ 
     List<String> attachFileNameList = new ArrayList<String>(); 
     int count = mimeMultipart.getCount(); 
     for (int i = 0; i < count; i++) { 
      BodyPart bodyPart = mimeMultipart.getBodyPart(i); 
      if("ATTACHMENT".equalsIgnoreCase(bodyPart.getDisposition())){ 
       attachFileNameList.add(bodyPart.getFileName()); 
      } 
     } 
     return attachFileNameList; 
    } 
+0

“ATTACHMENT” - > Part.ATTACHMENT, “INLINE” - > Part.INLINE –

+1

请考虑为解决方案的工作原理添加说明,以及与提问者采用的方法有何不同。 –

相关问题