[英]Java : Using Javamail to read email
我一直在研究一個程序,假設使用javamail來讀取收件箱,如果電子郵件包含特定的字符串,則應該打開它。
首先,這是我第一次嘗試使用這個javamail api - 我很確定我的屬性都搞砸了 - 有人能給我提示正確設置javamail的屬性嗎?
其次,似乎我可以通過API連接,但如果我嘗試搜索主題並且主題為空,我會得到一個空指針異常 - 如果我不嘗試將主題與“Ordretest”匹配,我得到沒有nullpointer - 任何提示將是一個很大的幫助:)
package vildereMail;
import java.util.Properties;
import javax.mail.Address;
import javax.mail.BodyPart;
import javax.mail.Folder;
import javax.mail.Message;
import javax.mail.MessagingException;
import javax.mail.Multipart;
import javax.mail.Session;
import javax.mail.Store;
import javax.mail.internet.InternetAddress;
import javax.mail.search.FromTerm;
import javax.mail.search.SearchTerm;
import javax.mail.search.SubjectTerm;
public class vildereMail {
public boolean match(Message message) {
try {
if (message.getSubject().contains("Ordretest")) {
System.out.println("match found");
return true;
}
} catch (MessagingException ex) {
ex.printStackTrace();
}
return false;
};
public static void main(String[] args) {
Properties props = System.getProperties();
props.setProperty("mail.store.protocol", "imaps");
props.put("mail.imap-mail.outlook.com.ssl.enable", "true");
props.put("mail.pop3.host", "outlook.com");
props.put("mail.pop3.port", "995");
props.put("mail.pop3.starttls.enable", "true");
try {
Session session = Session.getInstance(props, null);
Store store = session.getStore();
store.connect("imap-mail.outlook.com", "myEmail@live.dk", "MyPassword");
session.setDebug(true);
Folder inbox = store.getFolder("INBOX");
inbox.open(Folder.READ_ONLY);
SearchTerm sender = new FromTerm(new InternetAddress("myMail@live.dk"));
Message[] messages = inbox.search(sender);
System.out.println(messages);
for (int i = 0 ; i < messages.length ; i++) {
System.out.println(messages[i].getSubject());
if (messages[i].getSubject().equals(null)) {
System.out.println("null in subject");
break;
}
else if (messages[i].getSubject().contains("Ordretest")){
System.out.println("1 match found");
}
else {
System.out.println("no match");
}
}
System.out.println("no more messages");
store.close();
} catch (Exception mex) {
mex.printStackTrace();
}
}
}
如果不知道您獲得NPE(空指針異常)的哪一行,我猜它會出現在這里:
if (messages[i].getSubject().equals(null))
如果getSubject()返回null並且您嘗試執行.equals(),它將拋出一個NPE(因為您嘗試調用方法)。 所以嘗試將其重寫為(假設您的消息對象不能為null):
if (messages[i].getSubject() == null)
從哪兒開始...
您是否找到了JavaMail FAQ ?
你可以擺脫所有的屬性設置,因為他們沒有做任何事情,因為你使用的是“imaps”協議,而不是“pop3”協議。
正如其他人所解釋的那樣,getSubject方法可能會返回null,因此您需要檢查它。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.