如何修复Java Mail在while循环中不显示新电子邮件的问题



我正在制作一个脚本,使用电子邮件打开和关闭我的灯,除了它不会更新到最新的电子邮件之外,一切都正常,我不知道为什么。我在网上找不到任何东西,也没有尝试任何东西,因为我完全迷路了。BTW了解更多信息,脚本第一次运行时会运行最新的电子邮件,但在之后不会再这样做

这是我的代码,请帮助

根据我的理解,while循环应该是找到一个主题,然后检查它是否符合我要求它寻找的内容,然后它是否会到达顶部,再次检查最近的主题,然后再检查它是否是我想要的,然后一遍又一遍地做

import java.util.Properties;
import javax.mail.Folder;
import javax.mail.Message;
import javax.mail.MessagingException;
import javax.mail.NoSuchProviderException;
import javax.mail.Session;
import javax.mail.Store;

public class GetEmails {
public static void on(){
SSH on = new SSH();
on.command = "python3 on.py";
on.run();
}
public static void off(){
SSH off = new SSH();
off.command = "python3 off.py";
off.run();
}
public static void check(String host, String storeType, String user,
String password)
{
try {
//create properties field
Properties properties = new Properties();
properties.put("mail.pop3.host", host);
properties.put("mail.pop3.port", "995");
properties.put("mail.pop3.starttls.enable", "true");
Session emailSession = Session.getDefaultInstance(properties);
//create the POP3 store object and connect with the pop server
Store store = emailSession.getStore("pop3s");
store.connect(host, user, password);
//create the folder object and open it
Folder emailFolder = store.getFolder("INBOX");
emailFolder.open(Folder.READ_ONLY);
// retrieve the messages from the folder in an array
Message[] messages = emailFolder.getMessages();

boolean power = true;
while(true){
int i = messages.length - 1;
Message message = messages[i];
String subject = message.getSubject();
//                System.out.println(subject);
if(subject.equals("+myRoom") & power == false){
on();
power = true;
System.out.println("Light on");
}
else if (subject.equals("-myRoom") & power == true){
off();
power = false;
System.out.println("Light Off");
}
else{
continue;
}
}

} catch (NoSuchProviderException e) {
e.printStackTrace();
} catch (MessagingException e) {
e.printStackTrace();
} catch (Exception e) {
e.printStackTrace();
}
}
public static void main(String[] args) {
String host = "pop.gmail.com";// change accordingly
String mailStoreType = "pop3";
String username = "EMAIL@gmail.com";// change accordingly
String password = "PASSWORD";// change accordingly
check(host, mailStoreType, username, password);
}
}

问题是,您只在while循环之前调用getMessage((,然后在while环路中不断检查同一组下载的消息。

您需要更改while循环来下载最新的(一组(消息。

我还要指出的是,您的代码没有考虑到接收非命令消息的可能性,这些非命令消息可能会将最新的命令消息推送到";不是最新的";插槽(例如,最新的命令消息可能具有索引messages.length - 2,而非命令消息具有messages.length - 1索引(,也不考虑由于网络中断或服务器断开连接(由于多种原因,这种情况总是发生(而断开连接的可能性。

最新更新