Не удается загрузить вложение с помощью почты Java - PullRequest
0 голосов
/ 03 ноября 2019

Я пытался загрузить вложение из почтового ящика, но не смог. Я могу прочитать имя вложения из части тела, но не могу скачать вложение. Я пытался устранить неполадки с помощью некоторых операторов печати внутри циклов и выяснил, что я не могу попасть в третий блок if внутри второго цикла, вместо этого непосредственно переходит к оператору else Пожалуйста, помогите.

public static void attachment(String host, String storeType, String user,String password) throws Exception {
    try {
        //create properties field
        Properties properties = new Properties();

        properties.put("mail.imap.host",host);
        properties.put("mail.imap.port", "993");
        properties.put("mail.imap.starttls.enable", "true");
        properties.put("mail.imaps.ssl.trust", "*")
        properties.setProperty("mail.imap.socketFactory.class","javax.net.ssl.SSLSocketFactory");
        properties.setProperty("mail.imap.socketFactory.fallback", "false");
        properties.setProperty("mail.imap.socketFactory.port",String.valueOf(993));
        Session emailSession = Session.getDefaultInstance(properties);

        //create the imap store object and connect with the pop server

        Store store = emailSession.getStore("imap");

        store.connect(host, user, password);

        //create the folder object and open it

        Folder inboxFolder = store.getFolder("INBOX");

        inboxFolder.open(Folder.READ_ONLY);

        // retrieve the messages from the folder in an array

        Message[] arrayMessages=inboxFolder.getMessages();

        int n=arrayMessages.length;
        System.out.println("Total messages "+n)

        //attachment directory
        File tempDir = new File(System.getProperty("java.io.tmpdir"));
        String saveDirectory=tempDir.getAbsolutePath();


        for (int i = n-5; i<n; i++)
        {
            Message message = arrayMessages[i];

            Address[] fromAddress = message.getFrom();
            String from = fromAddress[0].toString();

            String subject = message.getSubject();
            String sentDate = message.getSentDate().toString();

            if(from.contains("System Administrator") && subject.contains("Test Test"))
            {

                String contentType = message.getContentType();

                String messageContent = "";

                // store attachment file name, separated by comma
                String attachFiles = "";

                if (contentType.contains("multipart"))
               {
                   System.out.println("Inside the 2nd if");

                    // content may contain attachments

                    Multipart multiPart = (Multipart) message.getContent();

                    int numberOfParts = multiPart.getCount();
                    System.out.println("Number of Parts: "+numberOfParts);

                    for (int partCount = 0; partCount < numberOfParts; partCount++) 
                    {
                        BodyPart bodyPart = multiPart.getBodyPart(partCount);

                        String fileName = bodyPart.getFileName();

                        System.out.println("File name: "+fileName);

                        String disposition = bodyPart.getDisposition();


                        if ( (disposition != null) && ( Part.ATTACHMENT.equalsIgnoreCase(disposition) ) )
                        {
                            // this part is attachment
                            System.out.println("Inside the 3rd if");

                            attachFiles += fileName + ", ";

                            bodyPart.saveFile(saveDirectory + File.separator + fileName);

                        } 
                        else {
                            System.out.println("In the else statement");
                                // this part may be the message content
                                messageContent = bodyPart.getContent().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 Attachments: " + attachFiles);
            }
        }       
        }
        inboxFolder.close(false);
        store.close();

    } catch (NoSuchProviderException e) {
        e.printStackTrace();
    } catch (MessagingException e) {
        e.printStackTrace();
    } catch (Exception e) {
        e.printStackTrace();
    }
}
...