| 注册
请输入搜索内容

热门搜索

Java Linux MySQL PHP JavaScript Hibernate jQuery Nginx
pmw4
10年前发布

利用Apache commons net 包实现简单的POP3邮件

Apache commons net中,对邮件的处理是非常强悍的,因此可以自己做一些邮件方面的工作。搭建邮件服务器的事情相对比较麻烦,我们还是直接利用现成的邮件服务器来使用,比如通过QQ邮箱收一些邮件。

在使用这个之前,要确保自己有一个邮箱,并且知道这个邮箱的POP3服务协议地址,以及这个邮箱对应的用户名和密码。

利用net 包实现简单的POP3邮件代码如下:

import java.io.BufferedReader;    import java.io.IOException;    import java.util.Locale;         import org.apache.commons.net.pop3.POP3Client;    import org.apache.commons.net.pop3.POP3MessageInfo;         public classEasyPOP3Mail {        public static void main(String[] args) {            POP3Clientpop3 = newPOP3Client();            try {                pop3.setDefaultPort(110);                          // We want to timeout if a response takes longer than 60 seconds                pop3.setDefaultTimeout(60000);                pop3.connect("pop.qq.com");//QQ邮件~如果邮箱不可用,换一个可用的                // 输入你的QQ号作为名称 QQ密码作为邮箱密码                if (pop3.login("fanfangming","123456")){                    POP3MessageInfo[]messages = pop3.listMessages();                    if (messages == null)                    {                        System.err.println("Could not retrieve message list.");                        pop3.disconnect();                        return;                    }                    else if (messages.length== 0)                    {                        System.out.println("No messages");                        pop3.logout();                        pop3.disconnect();                        return;                    }                         for (POP3MessageInfo msginfo : messages) {                        BufferedReader reader =(BufferedReader) pop3.retrieveMessageTop(msginfo.number, 0);                             if (reader == null) {                            System.err.println("Could not retrieve message header.");                            pop3.disconnect();                            System.exit(1);                        }                        printMessageInfo(reader,msginfo.number);                    }                         pop3.logout();                    pop3.disconnect();                }                 }catch(Exception e) {                System.out.println("失败");                e.printStackTrace();            }             }              public static final voidprintMessageInfo(BufferedReader reader, int id) throws IOException {            String from = "";            String subject = "";            String line;            while ((line = reader.readLine()) != null)            {            Stringlower = line.toLowerCase(Locale.CHINESE);                if (lower.startsWith("from: ")) {                    from = line.substring(6).trim();                } else if (lower.startsWith("subject: ")){                    subject =line.substring(9).trim();                }            }            System.out.println(Integer.toString(id) + " From: "+ from + " Subject: " + subject);       }    }