Apache Commons NET, the processing of mail is very strong, so you can do some of their own mail work. Building a mail server is relatively troublesome, we still directly use the ready-made mail server, such as through the QQ mailbox to receive some mail.
Before using this, make sure you have a mailbox and know the POP3 service agreement address for this mailbox and the user name and password for this mailbox.
Using NET Package implementation Simple POP3 message code is as follows:
Package test.ffm83.commons.net.mail;
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 class Easypop3mail {
Public static void Main (string[] args) {
POP3CLIENTPOP3 = newpop3client ();
Try {
POP3. Setdefaultport (110);
//We want to timeout if a response takes longer than
Pop3.setdefaulttimeout (60000);
Pop3.connect ("pop.qq.com"); //QQ Mail ~ If the mailbox is unavailable, change to an available
// type in your QQ number as the name QQ Password as email password
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 (" failure ");
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);
}
}
The results of the operation are as follows:
No messages
There are currently no messages.
Use Apache Commons NET package to implement simple POP3 mail