日期:2014-05-17 浏览次数:20801 次
import java.io.BufferedReader; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import java.util.Properties; import javax.mail.Folder; import javax.mail.Message; import javax.mail.MessagingException; import javax.mail.Multipart; import javax.mail.NoSuchProviderException; import javax.mail.Part; import javax.mail.Session; import javax.mail.Store; public class ReceiveEmail { public static void receive() { Properties props = new Properties(); //存储接收邮件服务器使用的协议,这里以POP3为例 props.setProperty("mail.store.protocol", "pop3"); //设置接收邮件服务器的地址,这里还是以网易163为例 props.setProperty("mail.pop3.host", "pop3.sina.cn"); //根据属性新建一个邮件会话. Session session=Session.getInstance(props); try { //从会话对象中获得POP3协议的Store对象 Store store = session.getStore("pop3"); //如果需要查看接收邮件的详细信息,需要设置Debug标志 session.setDebug(false); //连接邮件服务器 store.connect("pop3.sina.cn", "用户名", "密码"); //获取邮件服务器的收件箱 Folder folder = store.getFolder("INBOX"); //以只读权限打开收件箱 folder.open(Folder.READ_ONLY); //获取收件箱中的邮件,也可以使用getMessage(int 邮件的编号)来获取具体某一封邮件 Message[] message = folder.getMessages(); for (int i=0; i < message.length; i++) { Part messPart = message[i]; Object content = message[i].getContent(); messPart = ((Multipart)content).getBodyPart(0); InputStream in = messPart.getInputStream(); BufferedReader reader = new BufferedReader(new InputStreamReader(in)); String str = reader.readLine(); while (str!=null){ System.out.println(str); str=reader.readLine(); } } //关闭连接 folder.close(false); store.close(); } catch (NoSuchProviderException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (MessagingException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } } public static void main(String[] args) { receive(); System.out.println("ok"); } }