Search code examples
javaautomationoutlookjakarta-mail

How to download Multiple Attachment's from a Outlook Mail Using Java?


Hi i am trying to use the below code to download attachments from all the unread out look mail .

Problem While downloading multiple attachment

Right after downloading the first attachment and then when moving on to the next I am getting the below error

java.io.FileNotFoundException: Y:\pdf\=?utf-8?B?QW5udWxhdGlvbiAtIEF2ZW5hbnQgZGUgcsOpc2lsaWF0aW9uLlBERg==?= (The filename, directory name, or volume label syntax is incorrect)
   at java.base/java.io.FileOutputStream.open0(Native Method)
   at java.base/java.io.FileOutputStream.open(FileOutputStream.java:291)
   at java.base/java.io.FileOutputStream.<init>(FileOutputStream.java:234)
   at java.base/java.io.FileOutputStream.<init>(FileOutputStream.java:184)
   at javax.mail.internet.MimeBodyPart.saveFile(MimeBodyPart.java:951)
   at javax.mail.internet.MimeBodyPart.saveFile(MimeBodyPart.java:981)
   at Email_Attachment.test.main(test.java:90)

Below is the Code I am using

   package Email_Attachment;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.util.Properties;

import javax.mail.Address;
import javax.mail.Flags;
import javax.mail.Folder;
import javax.mail.Session;
import javax.mail.Store;
import javax.mail.internet.MimeBodyPart;
import javax.mail.search.FlagTerm;

import javax.mail.Message;
import javax.mail.MessagingException;
import javax.mail.Multipart;
import javax.mail.NoSuchProviderException;
import javax.mail.Part;
import javax.mail.PasswordAuthentication;
public class test  {

   public static void main(String[]args)throws Exception,FileNotFoundException {
     
         Properties props = System.getProperties();
         
         //String imapProtocol = System.getgetImapSsl() != null && server.getImapSsl() == true ? "imaps" : "imap";
       props.setProperty("mail.store.protocol", "imap");
       props.setProperty("mail.imap.ssl.enable", "true");
       props.setProperty("mail.imap.partialfetch", "false");
       props.put("mail.mime.base64.ignoreerrors", "true");
       
       //props.put("mail.imap.auth", "true");
        
       Session mailSession = Session.getDefaultInstance(props
                , 
              new javax.mail.Authenticator(){
                  protected PasswordAuthentication getPasswordAuthentication() {
                      return new PasswordAuthentication("username", "password");// Specify the Username and the PassWord
                  }
          });
       String test = "password";
    System.out.println(test);
       mailSession.setDebug(true);
       try {
      Store store = mailSession.getStore("imap");
      
       store.connect( "outlook.office365.com","username", "password");// Specify the Username and the PassWord
           

       Folder folderInbox = store.getFolder("INBOX");
       folderInbox.open(Folder.READ_ONLY);

       // fetches new messages from server
      
       Message[] messages = folderInbox.search(new FlagTerm(new Flags(Flags.Flag.SEEN), false));
                

       for (int i = 0; i < messages.length; i++) {
           Message message = messages[i];
           Address[] fromAddress = message.getFrom();
           String from = fromAddress[0].toString();
           String subject = message.getSubject();
           String sentDate = message.getSentDate().toString();

           String contentType = message.getContentType();
           String messageContent = "";

           // store attachment file name, separated by comma
           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);
                   if (Part.ATTACHMENT.equalsIgnoreCase(part.getDisposition())) {
                       // this part is attachment
                       String fileName = part.getFileName();
                       attachFiles += fileName + ", ";
                       part.saveFile("Y:\\pdf\\" + File.separator + fileName);
                   } else {
                       // this part may be the message content
                       messageContent = part.getContent().toString();
                   }
               }

               if (attachFiles.length() > 1) {
                   attachFiles = attachFiles.substring(0, attachFiles.length() - 2);
               }
           } else if (contentType.contains("text/plain")
                   || contentType.contains("text/html")) {
               Object content = message.getContent();
               if (content != null) {
                   messageContent = content.toString();
               }
           }

           // print out details of each message
           System.out.println("Message #" + (i + 1) + ":");
           System.out.println("\t From: " + from);
           System.out.println("\t Subject: " + subject);
           System.out.println("\t Sent Date: " + sentDate);
           System.out.println("\t Message: " + messageContent);
           System.out.println("\t Attachments: " + attachFiles);
       }

       // disconnect
       folderInbox.close(false);
       store.close();
   } catch (NoSuchProviderException ex) {
       System.out.println("No provider for pop3.");
       ex.printStackTrace();
   } catch (MessagingException ex) {
       System.out.println("Could not connect to the message store");
       ex.printStackTrace();
   } catch (IOException ex) {
       ex.printStackTrace();
   }


 }}

I am very New to Java Mail can anyone help me on this


Solution

  • Hi I made some changes to your code the reason why this happened is because your email attachments were encrypted by UTF-8,The below code changes should work for you.

    Message[] messages = folderInbox.search(new FlagTerm(new Flags(Flags.Flag.SEEN), false));
           for (int i = 0; i < messages.length; i++) {
                
           Message message = messages[i];
           Address[] fromAddress = message.getFrom();
           String from = fromAddress[0].toString();
           String subject = message.getSubject();
           String sentDate = message.getSentDate().toString();
           String saveDirectory =directory;
           String contentType = message.getContentType();
           String messageContent = "";
           String attachFiles = "";             
           if (contentType.contains("multipart")) {                  
               Multipart multiPart = (Multipart) message.getContent();
               int numberOfParts = multiPart.getCount();                                                       
               for (int partCount = 0; partCount < numberOfParts; partCount++) {
               MimeBodyPart part = (MimeBodyPart) multiPart.getBodyPart(partCount);
               if (Part.ATTACHMENT.equalsIgnoreCase(part.getDisposition())) {
                String fileName = part.getFileName();
                if (fileName.contains("=?utf-")) {
                String s1 = fileName;                           
                String s2=MimeUtility.decodeText(s1); 
                //System.out.println(s2);
                part.saveFile(saveDirectory + File.separator +"("+i+")"+s2);
                }else if(fileName.contains("Windows-1252")){
                      String V1= fileName;  
                      System.out.println("File is not a valid file"+V1);
                      //part.saveFile(saveDirectory + File.separator +"("+i+")"+fileName);
                }else {
                
                //System.out.println(fileName);
                part.saveFile(saveDirectory + File.separator +"("+i+")"+fileName);
                
                }
                } else {
                messageContent = part.getContent().toString();
                }
                }
                if (attachFiles.length() > 1) {
                attachFiles = attachFiles.substring(0, attachFiles.length() - 2);
                }
                } else if (contentType.contains("text/plain")|| contentType.contains("text/html")) {
                Object content = message.getContent();
                if (content != null) {
                messageContent = content.toString();
               }
           }
    
          
           System.out.println("Message #" + (i + 1) + ":");
           System.out.println("\t From: " + from);
           System.out.println("\t Subject: " + subject);
           System.out.println("\t Sent Date: " + sentDate);
           System.out.println("\t Message: " + messageContent);
           System.out.println("\t Attachments: " + attachFiles);
       }
    
       
       folderInbox.close(false);
       store.close();