java 中的 Gmail 附件下载问题

Gmail Attachment download issue in java

我正在 java 中使用 imap 从 gmail 下载音频文件。音频文件已成功下载并播放。通常在美国标准时间上午 5 点左右,文件未下载。得到像“java.lang.NullPointerException”这样的异常。昨天我遇到了这个问题,但今天同样的代码工作正常,音频文件被下载,我不知道如何管理这个以找到这个问题的根本原因。你能请任何人帮助我吗?

注意:添加了更多日志以了解用于测试目的的流程,

日志:

    TID: [-1234] [] [2021-02-22 03:01:15,925]  INFO {com.vb.service.EmailAttachmentDownload} -  ====UserName==== : vb.lead@qrsolutions.com.au {com.vb.service.EmailAttachmentDownload}
TID: [-1234] [] [2021-02-22 03:01:15,925]  INFO {com.vb.service.EmailAttachmentDownload} -  ====Password==== : e59851edd90156ff379e {com.vb.service.EmailAttachmentDownload}
TID: [-1234] [] [2021-02-22 03:01:15,925]  INFO {com.vb.service.EmailAttachmentDownload} -  ====FileName==== : 00432214294_rcvm0117_00800000210222130231.wav {com.vb.service.EmailAttachmentDownload}
TID: [-1234] [] [2021-02-22 03:01:15,925]  INFO {com.vb.service.EmailAttachmentDownload} -  ====SaveDirectory==== : /wso2/BulkPush/HarmonySourcePath/ {com.vb.service.EmailAttachmentDownload}
TID: [-1234] [] [2021-02-22 03:01:15,925]  INFO {com.vb.service.EmailAttachmentDownload} -  ====Download FileName==== : VB_TwoWayRecording_00432214294_rcvm0117_00800000210222130231.wav {com.vb.service.EmailAttachmentDownload}
TID: [-1234] [] [2021-02-22 03:01:15,925]  INFO {com.vb.service.EmailAttachmentDownload} -  ==== Logger Text ==== : Step 1. {com.vb.service.EmailAttachmentDownload}
TID: [-1234] [] [2021-02-22 03:01:15,925]  INFO {com.vb.service.EmailAttachmentDownload} -  ==== Logger Text ==== : Step SetSaveDirectory Method. {com.vb.service.EmailAttachmentDownload}
TID: [-1234] [] [2021-02-22 03:01:15,925]  INFO {com.vb.service.EmailAttachmentDownload} -  ==== Logger Text ==== : Step 2. {com.vb.service.EmailAttachmentDownload}
TID: [-1234] [] [2021-02-22 03:01:15,925]  INFO {com.vb.service.EmailAttachmentDownload} -  ==== Logger Text ==== : Step 3. {com.vb.service.EmailAttachmentDownload}
TID: [-1234] [] [2021-02-22 03:01:15,925]  INFO {com.vb.service.EmailAttachmentDownload} -  ==== Logger Text ==== : Step 4. {com.vb.service.EmailAttachmentDownload}
TID: [-1234] [] [2021-02-22 03:01:15,925]  INFO {com.vb.service.EmailAttachmentDownload} -  ==== Logger Text ==== : Step 5. {com.vb.service.EmailAttachmentDownload}
TID: [-1234] [] [2021-02-22 03:01:15,926]  INFO {com.vb.service.EmailAttachmentDownload} -  ==== Logger Text ==== : Step 7. {com.vb.service.EmailAttachmentDownload}
TID: [-1234] [] [2021-02-22 03:01:15,926]  INFO {com.vb.service.EmailAttachmentDownload} -  ==== Logger Text ==== : Step 8. {com.vb.service.EmailAttachmentDownload}
TID: [-1234] [] [2021-02-22 03:01:15,928]  INFO {com.vb.service.EmailAttachmentDownload} -  ==== Logger Text ==== : Step 6. {com.vb.service.EmailAttachmentDownload}
TID: [-1234] [] [2021-02-22 03:01:17,481]  INFO {com.vb.service.EmailAttachmentDownload} -  ==== Logger Text ==== : Step 9. {com.vb.service.EmailAttachmentDownload}
TID: [-1234] [] [2021-02-22 03:01:17,792]  INFO {com.vb.service.EmailAttachmentDownload} -  ==== Logger Text ==== : Step 10. {com.vb.service.EmailAttachmentDownload}
TID: [-1234] [] [2021-02-22 03:01:18,097]  INFO {com.vb.service.EmailAttachmentDownload} -  ==== Logger Text ==== : Step 11. {com.vb.service.EmailAttachmentDownload}
TID: [-1234] [] [2021-02-22 03:01:18,097]  INFO {com.vb.service.EmailAttachmentDownload} -  ==== Logger Text ==== : Step 12 - 0 {com.vb.service.EmailAttachmentDownload}
TID: [-1234] [] [2021-02-22 03:01:18,404]  INFO {com.vb.service.EmailAttachmentDownload} -  ==== Logger Text ==== : Step 13. {com.vb.service.EmailAttachmentDownload}
TID: [-1234] [] [2021-02-22 03:01:18,404]  INFO {com.vb.service.EmailAttachmentDownload} -  ==== Logger Text ==== : Step 14. {com.vb.service.EmailAttachmentDownload}
TID: [-1234] [] [2021-02-22 03:01:18,404]  INFO {com.vb.service.EmailAttachmentDownload} -  ==== Logger Text ==== : Step 15. {com.vb.service.EmailAttachmentDownload}
TID: [-1234] [] [2021-02-22 03:01:18,404]  INFO {com.vb.service.EmailAttachmentDownload} -  ==== Logger Text ==== : Step 16. {com.vb.service.EmailAttachmentDownload}
TID: [-1234] [] [2021-02-22 03:01:18,404]  INFO {com.vb.service.EmailAttachmentDownload} -  ==== Logger Text ==== : Step 46 - Exception Sequence {com.vb.service.EmailAttachmentDownload}
TID: [-1234] [] [2021-02-22 03:01:18,404]  INFO {com.vb.service.EmailAttachmentDownload} -  General/Common Exceptionjava.lang.NullPointerException {com.vb.service.EmailAttachmentDownload}
TID: [-1234] [] [2021-02-22 03:01:18,404]  INFO {com.vb.service.EmailAttachmentDownload} -  Exception Message:   [Ljava.lang.StackTraceElement;@24983d2b** Exception Message:   null {com.vb.service.EmailAttachmentDownload}
TID: [-1234] [] [2021-02-22 03:01:18,404]  INFO {com.vb.service.EmailAttachmentDownload} -  ==== Logger Text ==== : Step 47. {com.vb.service.EmailAttachmentDownload}

日志图像:

代码:

package JavaPackage;

import java.util.logging.Logger;
import java.io.File;
import java.io.IOException;
import java.util.Properties;


import javax.mail.Address;
import javax.mail.Flags;
import javax.mail.Folder;
import javax.mail.Message;
import javax.mail.MessagingException;
import javax.mail.Multipart;
import javax.mail.NoSuchProviderException;
import javax.mail.Part;
import javax.mail.PasswordAuthentication;
import javax.mail.Session;
import javax.mail.Store;
import javax.mail.internet.MimeBodyPart;
import javax.mail.search.FlagTerm;



public class GetEmailAttachment {
    private String saveDirectory;
    private static final Logger logger = Logger.getLogger(GetEmailAttachment.class.getName());

public static void main(String[] args) {
    logger.info("===Inside the attachment download class===");
    String host = "imap.gmail.com";

    String port = "995";
    
      String userName = "username"; 
      String password= "pwd"; 
      String inputFileName ="00432214294_rcvm0117_00800000210222130231.wav";
     String saveDirectory = "D:/HarmonyTemplate/Source";
     String downloadFileName = "VB_TwoWayRecording_TestAudio";
     logger.info("====UserName==== : " + userName);
        logger.info("====Password==== : " + password);
        logger.info("====FileName==== : " + inputFileName);
        logger.info("====SaveDirectory==== : " + saveDirectory);
        logger.info("====Download FileName==== : " + downloadFileName);

        GetEmailAttachment receiver = new GetEmailAttachment();
        logger.info("==== Logger Text ==== : Step 1.");
        receiver.setSaveDirectory(saveDirectory);
        logger.info("==== Logger Text ==== : Step 2.");
        receiver.downloadEmailAttachments(userName, password, inputFileName, downloadFileName);
     
}
public void setSaveDirectory(String dir) {
    logger.info("==== Logger Text ==== : Step SetSaveDirectory Method.");
    this.saveDirectory = dir;
}

public boolean downloadEmailAttachments(String userName, String password, String inputfileName,
        String downloadFileName) {
    
    try {
    logger.info("==== Logger Text ==== : Step 3.");
    Properties properties = new Properties();
    logger.info("==== Logger Text ==== : Step 4.");
    properties.setProperty("mail.host", "imap.gmail.com");
    properties.setProperty("mail.port", "995");
    properties.setProperty("mail.transport.protocol", "imaps");
    logger.info("==== Logger Text ==== : Step 5.");
    Session session = Session.getInstance(properties, new javax.mail.Authenticator() {
        protected PasswordAuthentication getPasswordAuthentication() {
            logger.info("==== Logger Text ==== : Step 6.");
            return new PasswordAuthentication(userName, password);
        }
    });
    logger.info("==== Logger Text ==== : Step 7.");
    

        // connects to the message store
        Store store = session.getStore("imaps");
        logger.info("==== Logger Text ==== : Step 8.");
        store.connect();
        logger.info("==== Logger Text ==== : Step 9.");
        Folder folderInbox = store.getFolder("INBOX");
        folderInbox.open(Folder.READ_WRITE);
        logger.info("==== Logger Text ==== : Step 10.");
        // fetches new messages from server
        Message[] arrayMessages = folderInbox.search(new FlagTerm(new Flags(Flags.Flag.SEEN), false));
        logger.info("==== Logger Text ==== : Step 11.");
        for (int i = 0; i < arrayMessages.length; i++) {
            logger.info("==== Logger Text ==== : Step 12 - " + i);
            Message message = arrayMessages[i];
            Address[] fromAddress = message.getFrom();
            logger.info("==== Logger Text ==== : Step 13.");
            String from = fromAddress[0].toString();
            logger.info("==== Logger Text ==== : Step 14.");
            String subject = message.getSubject();
            logger.info("==== Logger Text ==== : Step 15.");
            String sentDate = message.getSentDate().toString();
            logger.info("==== Logger Text ==== : Step 16.");
            if ((subject.replaceAll(" ", "").trim().toUpperCase().contains("AUTOMATICTWO-WAYRECORDING"))
                    || (subject.replaceAll(" ", "").trim().toUpperCase().contains("MESSAGENOTIFICATIONFROM"))) {
                logger.info("====== Inside the subject check of class mediator =======");
                String contentType = message.getContentType();
                String messageContent = "";

                // store attachment file name, separated by comma
                String attachFiles = "";
                logger.info("==== Logger Text ==== : Step 17.");
                if (contentType.contains("multipart")) {
                    logger.info("======Contains multipart values======");
                    // content may contain attachments
                    Multipart multiPart = (Multipart) message.getContent();
                    logger.info("==== Logger Text ==== : Step 18.");
                    int numberOfParts = multiPart.getCount();
                    logger.info("==== Logger Text ==== : Step 19.");
                    for (int partCount = 0; partCount < numberOfParts; partCount++) {
                        logger.info("==== Logger Text ==== : Step 20 - " + partCount);
                        MimeBodyPart part = (MimeBodyPart) multiPart.getBodyPart(partCount);
                        logger.info("==== Logger Text ==== : Step 21.");
                        if (Part.ATTACHMENT.equalsIgnoreCase(part.getDisposition())) {
                            logger.info("==== Logger Text ==== : Step 22.");
                            // this part is attachment
                            String fileName = part.getFileName();
                            logger.info("==== Logger Text ==== : Step 23.");
                            if (inputfileName.equals(fileName)) {
                                logger.info("==== Logger Text ==== : Step 24.");
                                attachFiles += fileName + ", ";
                                logger.info("====== Final Values ====== "
                                        + (saveDirectory + File.separator + downloadFileName));
                                part.saveFile(saveDirectory + File.separator + downloadFileName);
                                logger.info("==== Logger Text ==== : Step 25.");
                                return true;
                            }
                            logger.info("==== Logger Text ==== : Step 26.");
                        } else {
                            logger.info("==== Logger Text ==== : Step 27.");
                            // this part may be the message content
                            messageContent = part.getContent().toString();
                            logger.info("==== Logger Text ==== : Step 28.");
                        }
                    logger.info("==== Logger Text ==== : Step 29.");
                    }
                    logger.info("==== Logger Text ==== : Step 30.");
                    if (attachFiles.length() > 1) {
                        logger.info("==== Logger Text ==== : Step 31.");
                        attachFiles = attachFiles.substring(0, attachFiles.length() - 2);
                    }
                    logger.info("==== Logger Text ==== : Step 32.");
                } else if (contentType.contains("text/plain") || contentType.contains("text/html")) {
                    logger.info("==== Logger Text ==== : Step 33.");
                    Object content = message.getContent();
                    logger.info("==== Logger Text ==== : Step 34.");
                    if (content != null) {
                        logger.info("==== Logger Text ==== : Step 35.");
                        messageContent = content.toString();
                        logger.info("==== Logger Text ==== : Step 36.");
                    }
                    logger.info("==== Logger Text ==== : Step 37.");
                }
                logger.info("==== Logger Text ==== : Step 38.");

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

            }
            logger.info("==== Logger Text ==== : Step 39.");
        }
        logger.info("==== Logger Text ==== : Step 40.");
        // disconnect
        folderInbox.close(false);
        logger.info("==== Logger Text ==== : Step 41.");
        store.close();
        logger.info("==== Logger Text ==== : Step 42.");

    } catch (NoSuchProviderException ex) {
        logger.info("==== Logger Text ==== : Step 43 - Exception Sequence");
        logger.info("No provider for pop3." + ex);
        logger.info("Exception Message:   " + ex.getStackTrace() + "** " + "Exception Message:   " + ex.getMessage());
        ex.printStackTrace();
        //context.setProperty("EXCEPTION_MESSAGE_Raw", ex.toString());
    } catch (MessagingException ex) {
        logger.info("==== Logger Text ==== : Step 44 - Exception Sequence");
        logger.info("Could not connect to the message store" + ex);
        logger.info("Exception Message:   " + ex.getStackTrace() + "** " + "Exception Message:   " + ex.getMessage());
        ex.printStackTrace();
        //context.setProperty("EXCEPTION_MESSAGE_Raw", ex.toString());
    } catch (IOException ex) {
        logger.info("==== Logger Text ==== : Step 45 - Exception Sequence");
        logger.info("Exception in IO Files" + ex);
        logger.info("Exception Message:   " + ex.getStackTrace() + "** " + "Exception Message:   " + ex.getMessage());
        ex.printStackTrace();
        
    } catch (Exception ex) {
        logger.info("==== Logger Text ==== : Step 46 - Exception Sequence");
        logger.info("General/Common Exception" + ex);
        logger.info("Exception Message:   " + ex.getStackTrace() + "** " + "Exception Message:   " + ex.getMessage());
        ex.printStackTrace();
        logger.info(ex.toString());
        
    }
    
    logger.info("==== Logger Text ==== : Step 47.");
    return true;
}
}

你打印Log 16,然后打印Log 46抛出NullPointer。

你的问题出在:

  if ((subject.replaceAll(" ", "").trim().toUpperCase().contains("AUTOMATICTWO-WAYRECORDING"))
                    || (subject.replaceAll(" ", "").trim().toUpperCase().contains("MESSAGENOTIFICATIONFROM"))) {

     

因为你没有打印,“====== 在 class 调解器的主题检查中 ======= 在你捕获你的异常之前。

您的主题为空。

顺便说一句,你也不能保证在这之后通过。如果您不检查 != null

,您仍然可能在接下来的步骤中遇到另一个 NullPointer
Fix:    if ((subject != null && subject.replaceAll(" ", "").trim().toUpperCase().contains("AUTOMATICTWO-WAYRECORDING"))
                || (subject.replaceAll(" ", "").trim().toUpperCase().contains("MESSAGENOTIFICATIONFROM"))) {
     

这是可行的,因为如果 subject == null,它会很快失败并在不检查 subject.replaceAll.

的情况下存在 if 语句