JavaMail简单接收邮件

一个简单的例子,收取所有邮件并在控制台输出。

package cn.jmail.test;

 

import java.io.*;

import java.util.*;

import javax.mail.*;

 

public class MailReceives {

    public static void main(String[] args) {

        String pop3Server = "pop3.163.com";

        String protocol = "pop3";

        String username = "xxxx";

        String password = "xxxx";

        Properties prop = new Properties();

        prop.setProperty("mail.store.protocol", protocol);

        prop.setProperty("mail.pop3.host", pop3Server);

        Session mailSession = Session.getDefaultInstance(prop,null);

        mailSession.setDebug(false);

        try {

            Store store = mailSession.getStore(protocol);

            //登录验证

            store.connect(pop3Server,username,password);

            //获取邮箱账户

            Folder folder = store.getFolder("inbox");

            //设置访问权限

            folder.open(Folder.READ_WRITE);

            //获取所有邮件

            Message[] messages = folder.getMessages();

            for(int i=0; i<messages.length; i++){

                //主题

                String subject = messages[i].getSubject();

                //发送者地址

                String from = messages[i].getFrom()[0].toString();

                System.out.println("第" + (i+1) + "封邮件的主题为:" + subject + "\t发件人地址为:" + from);

                System.out.println("你想阅读此邮件吗(y/n)?");

                BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(System.in));

                String input = bufferedReader.readLine();

                if("y".equals(input.toLowerCase())){

                    messages[i].writeTo(System.out);

                }

            }

            folder.close(false);

            store.close();

        } catch (NoSuchProviderException e) {

            e.printStackTrace();

        } catch (MessagingException e) {

            e.printStackTrace();

        } catch (IOException e) {

            e.printStackTrace();

        }

    }

}

mail.jar和activation.jar  http://pan.baidu.com/s/1qW7MaS0

在这里和大家分享一本关于javamail的书籍《Java邮件开发详解》,大家可以自行百度一下。

你可能感兴趣的:(javamail)