2012-11-22 14 views
7

Il mio problema è il seguente:download del corpo del messaggio di posta elettronica contenente immagini inline in java

Ho impostato il mio codice per leggere le e-mail da un determinato account. Quella parte funziona perfettamente.

il problema è con l'analisi del messaggio di posta elettronica. Separazione di allegati e corpo dell'e-mail (contenente immagini in linea).

Il mio codice va in questo modo:

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

Il problema che ottengo è quando ho eseguito questo codice, ottengo un file HTML, ma le immagini in linea è sostituito da un segno un'immagine di errore per il quale indica l'immagine con nessuna fonte.

Per favore aiutatemi. Fammi sapere se sono necessarie ulteriori informazioni.

Ho provato anche salvare il corpo come un file .eml modificando:

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

a

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

ma ho ottenuto gli stessi risultati.

+0

"..da un segno per l'immagine di errore che indica l'immagine senza fonte." Sei sicuro che la fonte sia vuota? Hai controllato la sorgente HTML? – Janoz

+0

Controlla questo file HTML. https://www.dropbox.com/s/5evk4pjq721yo8m/mail.html – GSG

+0

Questo codice HTML ti mostrerà la sorgente dell'immagine mancante. – GSG

risposta

1

Ho scritto sotto il codice per convertire il testo del corpo del messaggio in pdf, comprese le immagini in linea. in codice ho sostituito il codice immagine (es: cid: [email protected]) con percorso immagine di download. Sto costruendo la "hashmap" per la chiave immagine e il percorso di download durante il download dell'immagine.

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

     } 

Scarica immagine in linea con passaggio articolo.

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(); 
      } 
     } 
    } 
1

I riferimenti alle immagini inline sono sostituiti da cid: URN come <img src="cid:SOMEID">, perché non ci sono nomi di file in un'email. SOMEID si riferisce al Content-ID degli "oggetti" Multipart.

Per farlo funzionare, è necessario memorizzare gli allegati multipart in file (ad es. Nomi temporanei) e sostituire gli URN cid con i nomi file reali.

+0

Sicuro! Ci proverò. – GSG

+0

Come questo è possibile ho lo stesso problema. Ho scaricato l'immagine in linea con successo ma non ho potuto rispondere src: cid con il mio percorso originale, per favore, dammi la soluzione se possibile e il prima possibile. –

+0

Non ha funzionato neanche per me. Sto ancora cercando una via d'uscita. – GSG

Problemi correlati