利用Apache commons net 包實現簡單的POP3郵件
Apache commons net中,對郵件的處理是非常強悍的,因此可以自己做一些郵件方面的工作。搭建郵件服務器的事情相對比較麻煩,我們還是直接利用現成的郵件服務器來使用,比如通過QQ郵箱收一些郵件。
在使用這個之前,要確保自己有一個郵箱,并且知道這個郵箱的POP3服務協議地址,以及這個郵箱對應的用戶名和密碼。
利用net 包實現簡單的POP3郵件代碼如下:
import java.io.BufferedReader;
import java.io.IOException;
import java.util.Locale;
import org.apache.commons.net.pop3.POP3Client;
import org.apache.commons.net.pop3.POP3MessageInfo;
public classEasyPOP3Mail {
public static void main(String[] args) {
POP3Clientpop3 = newPOP3Client();
try {
pop3.setDefaultPort(110);
// We want to timeout if a response takes longer than 60 seconds
pop3.setDefaultTimeout(60000);
pop3.connect("pop.qq.com");//QQ郵件~如果郵箱不可用,換一個可用的
// 輸入你的QQ號作為名稱 QQ密碼作為郵箱密碼
if (pop3.login("fanfangming","123456")){
POP3MessageInfo[]messages = pop3.listMessages();
if (messages == null)
{
System.err.println("Could not retrieve message list.");
pop3.disconnect();
return;
}
else if (messages.length== 0)
{
System.out.println("No messages");
pop3.logout();
pop3.disconnect();
return;
}
for (POP3MessageInfo msginfo : messages) {
BufferedReader reader =(BufferedReader) pop3.retrieveMessageTop(msginfo.number, 0);
if (reader == null) {
System.err.println("Could not retrieve message header.");
pop3.disconnect();
System.exit(1);
}
printMessageInfo(reader,msginfo.number);
}
pop3.logout();
pop3.disconnect();
}
}catch(Exception e) {
System.out.println("失敗");
e.printStackTrace();
}
}
public static final voidprintMessageInfo(BufferedReader reader, int id) throws IOException {
String from = "";
String subject = "";
String line;
while ((line = reader.readLine()) != null)
{
Stringlower = line.toLowerCase(Locale.CHINESE);
if (lower.startsWith("from: ")) {
from = line.substring(6).trim();
} else if (lower.startsWith("subject: ")){
subject =line.substring(9).trim();
}
}
System.out.println(Integer.toString(id) + " From: "+ from + " Subject: " + subject);
}
}
本文由用戶 pmw4 自行上傳分享,僅供網友學習交流。所有權歸原作者,若您的權利被侵害,請聯系管理員。
轉載本站原創文章,請注明出處,并保留原始鏈接、圖片水印。
本站是一個以用戶分享為主的開源技術平臺,歡迎各類分享!