如何在 java 邮件 api 中使用搜索方法

How to use the Search Method in java mail api

我正在使用 javamail api 创建一个搜索选项,它根据邮件主题中出现的关键字搜索 Gmail 文件夹中的电子邮件 这是我正在使用的代码

public class EGMail7 {
public static void main(String args[])
{
    Scanner sc = new Scanner(System.in);
    final String m10 = "abc@gmail.com";   
    final String n10 = "12345";
    string host = "smtp.gmail.com"; 
    try
    {
    Properties pro1 = new Properties();   
    pro1.put("mail.smtp.host", "smtp.gmail.com");    
    pro1.put("mail.smtp.socketFactory.port", "465");
    pro1.put("mail.smtp.socketFactory.class", "javax.net.ssl.SSLSocketFactory");  
    pro1.put("mail.smtp.auth", "true");   
    pro1.put("mail.smtp.port", "465");  
Session session = Session.getDefaultInstance(pro1, 
        new javax.mail.Authenticator()                  
{ 
    protected PasswordAuthentication getPasswordAuthentication()
{
        return new PasswordAuthentication(m10,n10);
        }
    }); 
    Store store = session.getStore("imaps");  
    store.connect(host, m10, n10); 
    Folder folderbox = store.getFolder("INBOX");
    folderbox.open(Folder.READ_ONLY);   
    SearchTerm search = new SearchTerm(){

        @Override
        public boolean match(Message message) {
            try
            {
                if(message.getSubject().contains([Keyword]))  
                {
                    return true;
                }
            }
            catch(Exception e)
            {
                System.err.println(e.getMessage());
            }
            return false;
        }

    };

    Message[] found = folderbox.search(search);

    int length = found.length;
    for(int i = 0;i<found.length;i++)
    {
        Message mess1 = found[i];
        System.out.println("->Message Number > "+i);
        System.out.println("->Message Subject >"+mess1.getSubject());
    }
    folderbox.close(true);
    store.close();
}
    catch(Exception e)
    {
        System.err.println(e.getMessage());
    }
   }
  }

我正在使用 Eclipse IDE,我面临的问题是无论我在 SearchTerm 方法中传递什么关键字,我总是最终得到 null Exception 和 Message[] Found Array 。我使用 Stack Trace 找出了这个 NullPointer 异常的问题,它位于

Message[] found = folderbox.search(search);

我似乎无法理解这里的问题是什么?

此致, 谢谢

PS - 如果有人也可以 post 更正后的代码,那就太好了 谢谢

此外,当我只是直接在 SearchTerm 中添加关键字时,它会给出类似

的错误
SearchTerm searchCon = new SearchTerm([Keyword]);

有2个错误 1.Cannot 实例化 SearchTerm 2.The 可序列化 class 不声明 Long 类型的静态最终序列 Verison UID 字段

所以我无法理解这里的错误是什么

您有例外,因为您有没有主题的邮件。声明应更正为;

if(message.getSubject() != null && message.getSubject().contains([Keyword]))  

您的代码中全是这些common JavaMail mistakes,请指正。

无需创建您自己的自定义 SearchTerm,只需使用 SubjectTerm:

SearchTerm search = new SubjectTerm(keyword);