Java客户端IMQP协议获取邮箱邮件列表

  • 授权密码获取

Java客户端与邮件服务器交互需要获取到邮件服务器的授权码,这里以qq邮箱为例,说明授权码的获取方式

登录qq邮箱后,点击主页的设置
在这里插入图片描述
点击账户

在这里插入图片描述

点击生成授权码

在这里插入图片描述

发送短信验证码后,可以得到最新的授权码

在这里插入图片描述

客户端程序代码实现

要想获取收件箱列表,此时需要用到的是imqp协议,这里需要知道qq服务器imqp协议的地址,发件邮箱与发件邮箱的授权码。
程序代码如下:

public class ReadUnreadEmails {
    
    


    static String code = "授权码";
    static String username = "qq邮箱";

    public static void main(String[] args) throws Exception {
    
    
        // QQ邮箱授权码
        String authCode = code;

        // QQ邮箱服务器地址和端口号
        String host = "imap.qq.com";

        // 获取Session对象
        Properties props = new Properties();
        props.put("mail.store.protocol", "imaps");
        Session session = Session.getInstance(props, null);

        // 连接到QQ邮箱服务器
        Store store = session.getStore("imaps");
        store.connect(host, username, code);

        // 打开收件箱文件夹
        Folder inbox = store.getFolder("INBOX");
        inbox.open(Folder.READ_ONLY);
        Message[] messages = inbox.getMessages();
        System.out.println("未读邮件数量:" + messages.length);
        for (Message message : messages) {
    
    
            System.out.println("Subject: " + message.getSubject());
            System.out.println("From: " + message.getFrom()[0]);
            System.out.println("Date: " + message.getSentDate());
            System.out.println("==========");
        }

        // 关闭收件箱文件夹和连接到QQ邮箱服务器的连接
        inbox.close(false);
        store.close();
    }
}

这里获取到的是所有的邮件列表,如果只想获取当天的收件列表,则可以使用以下代码:

public class ReadUnreadEmails {
    
    


    static String code = "授权码";
    static String username = "qq邮箱";

    public static void main(String[] args) throws Exception {
    
    
        // QQ邮箱授权码
        String authCode = code;

        // QQ邮箱服务器地址和端口号
        String host = "imap.qq.com";

        // 获取Session对象
        Properties props = new Properties();
        props.put("mail.store.protocol", "imaps");
        Session session = Session.getInstance(props, null);

        // 连接到QQ邮箱服务器
        Store store = session.getStore("imaps");
        store.connect(host, username, code);

        // 打开收件箱文件夹
        Folder inbox = store.getFolder("INBOX");
        inbox.open(Folder.READ_ONLY);
      
      	SearchTerm searchTerm = new ReceivedDateTerm(ComparisonTerm.GT, new Date());
        Message[] messages = inbox.search(searchTerm);
      
        System.out.println("未读邮件数量:" + messages.length);
        for (Message message : messages) {
    
    
            System.out.println("Subject: " + message.getSubject());
            System.out.println("From: " + message.getFrom()[0]);
            System.out.println("Date: " + message.getSentDate());
            System.out.println("==========");
        }

        // 关闭收件箱文件夹和连接到QQ邮箱服务器的连接
        inbox.close(false);
        store.close();
    }
}

猜你喜欢

转载自blog.csdn.net/qq_43750656/article/details/131829100
今日推荐