JavaMail详解(五)——身份验证 - 高飞网
89 人阅读

JavaMail详解(五)——身份验证

2016-11-22 16:11:16

    前面介绍了邮件的验证和读取,在连接邮件的Store时,我们传递了身份验证证书(用户名和密码)连同host。接下来我配置Properties,通过自定义身份验证实例来调用Session。一下示例通过对CheckingMail修改,使用自定义Authentication类,如下:


import java.util.Properties;

import javax.mail.Folder;
import javax.mail.Message;
import javax.mail.MessagingException;
import javax.mail.NoSuchProviderException;
import javax.mail.PasswordAuthentication;
import javax.mail.Session;
import javax.mail.Store;

public class CheckingMails2 {
    public static void check(String host, String storeType, final String user, final String password) {
        try {

            Properties properties = new Properties();

            properties.put("mail.pop3s.host", host);
            properties.put("mail.pop3s.port", "995");
            properties.put("mail.pop3s.starttls.enable", "true");
            
            
            Session emailSession = Session.getInstance(properties, new javax.mail.Authenticator() {
                @Override
                protected PasswordAuthentication getPasswordAuthentication() {
                    return new PasswordAuthentication(user, password);
                }

            });

            // 创建POP3 Sotre对象并连接到pop服务
            Store store = emailSession.getStore("pop3s");

            store.connect();

            // 创建Folder对象并打开它
            Folder emailFolder = store.getFolder("INBOX");
            emailFolder.open(Folder.READ_ONLY);

            // 从文件夹中以数组的形式读取消息并打印出来
            Message[] messages = emailFolder.getMessages();
            System.out.println("messages.length---" + messages.length);

            for (int i = 0, n = messages.length; i < n; i++) {
                Message message = messages[i];
                System.out.println("---------------------------------");
                System.out.println("Email Number " + (i + 1));
                System.out.println("Subject: " + message.getSubject());
                System.out.println("From: " + message.getFrom()[0]);
                System.out.println("Text: " + message.getContent().toString());

            }

            // 关闭Store和Folder对象
            emailFolder.close(false);
            store.close();

        } catch (NoSuchProviderException e) {
            e.printStackTrace();
        } catch (MessagingException e) {
            e.printStackTrace();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    public static void main(String[] args) {

        String host = "pop.163.com";// change accordingly
        String mailStoreType = "pop3";
        String username = "xxxxxxxx@163.com";// change accordingly
        String password = "xxxxxx";// change accordingly

        check(host, mailStoreType, username, password);

    }
}


还没有评论!
23.22.61.134