如何使用 Java 从 Outlook 邮件下载多个附件?

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

您好,我正在尝试使用以下代码从所有未读邮件中下载附件。

下载多个附件时出现问题

在下载第一个附件然后继续下一个附件时,我收到以下错误

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)

下面是我使用的代码

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


 }}

我对 Java 邮件还很陌生 谁能帮我解决这个问题

您好,我对您的代码进行了一些更改,这是因为您的电子邮件附件是用 UTF-8 加密的,下面的代码更改应该适合您。

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