protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
Properties props = System.getProperties();
props.setProperty("mail.store.protocol", "imaps");
try {
Session session = Session.getDefaultInstance(props, null);
Store store = session.getStore("imaps");
store.connect("imap.gmail.com", "abc@ymail.com", "abcpqr");
Folder inbox = store.getFolder("INBOX");
inbox.open(Folder.READ_WRITE);
SimpleDateFormat myFormatter = new SimpleDateFormat("yyyy-MM-dd", Locale.US);
Message[] msg = inbox.getMessages();
int totalmessages = inbox.getMessageCount();
int unreadmessages = inbox.getUnreadMessageCount();
System.out.println("total message" + totalmessages);
System.out.println("total unreadmessages" + unreadmessages);
int count, u = 0, k1 = 0;
for (count = totalmessages - 1; k1 < unreadmessages; count--) {
System.out.println("Details of" + (++u) + "message");
Address[] in = msg[count].getFrom();
k1++;
for (Address address: in ) {
System.out.println("FROM:" + address.toString());
}
String subject = msg[count].getSubject();
System.out.println("subject is:" + subject);
if (subject.toLowerCase().contains("rasa lsi training inquiry")) {
System.out.println("IS SEEN : " + msg[k1].isSet(Flag.RECENT));
if (msg[k1].isSet(Flags.Flag.RECENT)) {
System.out.println("Read");
}
msg[k1].setFlag(Flag.SEEN, true);
Flags flags = new Flags("fetched");
msg[count].setFlags(flags, true);
Multipart mp = (Multipart) msg[count].getContent();
BodyPart bp = mp.getBodyPart(1);
String date = myFormatter.format(msg[count].getSentDate());
System.out.println("SENT DATE:" + date);
}
}
}
}
答案 0 :(得分:1)
System.out.println("subject is:" + subject);
当主题为空时,这行代码会给出java.lang.NullPointerException
。
让null
安全完成。
System.out.println("subject is:" + subject == null? "":subject);
if (subject != null && subject.toLowerCase().contains("rasa lsi training inquiry")){
如果我理解您打算收到未读邮件并正确检查主题的意图。您只需提取未读邮件即可简化代码。
Flags seen = new Flags(Flags.Flag.SEEN);
FlagTerm fetchUnreadMails = new FlagTerm(seen, false);
Message unreadMessages[] = inbox.search(fetchUnreadMails);
Calendar permittedDate = Calendar.getInstance();
permittedDate.add(Calendar.DATE, -10);
for(Message message : unreadMessages){
if (sendDate.after(permittedDate.getTime()) && m.getSubject() != null && m.getSubject().toLowerCase().contains("rasa lsi training inquiry")) {
}
}