Rewrite the use of JavaMail POP3 to receive the letter JavaBean
Last Update:2017-02-28
Source: Internet
Author: User
/*
*author:tyfun
*datetime:2003.01.10
*package:com.westarsoft.mail
*/
Package com.westarsoft.mail;
Import javax.mail.*;
Import javax.mail.internet.*;
Import java.util.*;
Import java.io.*;
public class Getmail {
public static string receive (string Popserver, String popuser, String Poppassword) {
String mailcontent = "";
Store store = null;
Folder folder = null;
try {
Properties props = System.getproperties ();
Session session = Session.getdefaultinstance (props, null);
store = Session.getstore ("POP3");
Store.connect (Popserver, Popuser, Poppassword);
folder = Store.getdefaultfolder ();
if (folder = = null) throw new Exception ("No default folder");
folder = Folder.getfolder ("INBOX");
if (folder = = null) throw new Exception ("No POP3 INBOX");
Folder.open (folder.read_only);
message[] msgs = Folder.getmessages ();
for (int msgnum = 0; msgnum < msgs.length; msgnum++) {
Mailcontent = mailcontent + getMessage (Msgs[msgnum]) + "\n\n\n\n";
}
}
catch (Exception ex) {
Ex.printstacktrace ();
}
finally {
try {
if (Folder!=null) Folder.close (false);
if (store!=null) store.close ();
}
catch (Exception ex2) {
Ex2.printstacktrace ();
}
}
return mailcontent;
}
public static String getMessage (Message message) {
String mailcontent = null;
try {
String from = ((internetaddress) message.getfrom () [0]). getpersonal ();
if (from==null) from = ((internetaddress) message.getfrom () [0]). getaddress ();
Mailcontent = "From:" +from;
String subject = Message.getsubject ();
Mailcontent = mailcontent + "\ n" + "SUBJECT:" +subject;
Part messagepart = message;
Object content = Messagepart.getcontent ();
if (content instanceof Multipart) {
MessagePart = ((Multipart) content). Getbodypart (0);
Mailcontent = mailcontent + "\ n" + "[Multipart message]";
}
Mailcontent = mailcontent + "\ n" + "CONTENT:" +content.tostring ();
String ContentType = Messagepart.getcontenttype ();
Mailcontent = mailcontent + "\ n" + "CONTENT:" +contenttype;
if (Contenttype.startswith ("Text/plain") | | | contenttype.startswith ("text/html")) {
InputStream is = Messagepart.getinputstream ();
BufferedReader reader = new BufferedReader (new InputStreamReader (IS));
String thisline = Reader.readline ();
while (Thisline!=null) {
Mailcontent = mailcontent + "\ n" +thisline;
Thisline = Reader.readline ();
}
}
}
catch (Exception ex) {
Ex.printstacktrace ();
}
return mailcontent;
}
}
<%
Getmail mail = new Getmail ();
String content = mail.receive ("pop3.server.com", "User", "password");
if ((Content.trim () = = null) | | (Content.trim () = "")) {
System.out.println ("No mail!");
}
else {
System.out.println ("You got a new mail!");
}
%>