问题描述:
用pop3收取gmail的邮件 入口参数: 用户名 / 密码 做一个线程,每15分钟检查一次邮箱,收取邮箱的邮件,并解码后将标题显示出来 当我看完问题后,灵机一动,马上想到用java.util.TimerTask 和java.util.Timer类实现是最合适不过,虽然用线程也可以,可是会付出一些不必要的劳动;并且TimerTask类也是依靠线程来实现功能的 代码如下: java 代码- 测试类:
- import java.util.*;
- public class Test{
- public static void main(String[] args)throws Exception{
- MailTimerTask task=new MailTimerTask();
- Timer mailTimer=new Timer();
- mailTimer.schedule(task,2000,15*60*1000);
- }
- }
- import java.util.*;
- import java.io.UnsupportedEncodingException;
- import java.security.*;
- import java.util.Properties;
- import javax.mail.*;
- import javax.mail.internet.InternetAddress;
- import javax.mail.internet.MimeUtility;
- import java.lang.RuntimeException;
- public class MailTimerTask extends TimerTask{
- private static Store store=null;
- //静态初始化模块
- //保证后台只存在一个Store 连接
- static{
- try{
- connect("@mailName","@mailPassword");
- }catch(Exception e){
- e.printStackTrace();
- }
- }
- public void run(){
- try{
- System.out.println("正在读取邮箱");
- this.printNewMails(this.getNewMails("@mailName","mailPassword"));
- }catch(Exception e){
- e.printStackTrace();
- }
- }
- public static void connect(String mailName,String mailPassword)throws Exception{
- Security.addProvider(new com.sun.net.ssl.internal.ssl.Provider());
- final String SSL_FACTORY = "javax.net.ssl.SSLSocketFactory";
- Properties props = System.getProperties();
- props.setProperty("mail.pop3.socketFactory.class", SSL_FACTORY);
- props.setProperty("mail.pop3.socketFactory.fallback", "false");
- props.setProperty("mail.pop3.port", "995");
- props.setProperty("mail.pop3.socketFactory.port", "995");
- Session session = Session.getDefaultInstance(props,null);
- URLName urln = new URLName("pop3","pop.gmail.com",995,null, mailName,mailPassword);
- store = session.getStore(urln);
- store.connect();
- }
- public Message[] getNewMails(String mailName,String mailPassword)throws Exception{
- //当Store实例没有存在连接时
- if(store.isConnected()){
- connect(mailName,mailPassword);
- }
- Folder inbox = store.getFolder("INBOX");
- inbox.open(Folder.READ_ONLY);
- FetchProfile profile = new FetchProfile();
- profile.add(FetchProfile.Item.ENVELOPE);
- //假定存在没有阅读的邮件为新邮件
- if(inbox.getUnreadMessageCount()>0){
- int fetchCount=inbox.getMessageCount()-inbox.getUnreadMessageCount();
- if(fetchCount==0){
- return inbox.getMessages();
- }
- Message[] messages = inbox.getMessages(1,2);
- return messages;
- }
- else{
- System.out.println("不存在新邮件");
- throw new RuntimeException("不存在新邮件");
- }
- }
- public void printNewMails(Message[] msgs)throws Exception{
- for(Message msg:msgs){
- String text=msg.getSubject();
- if (text == null)
- System.out.println("该邮件无题");
- else if (text.startsWith("=GBK") || text.startsWith("=gb2312"))
- text = MimeUtility.decodeText(text);
- else
- text = new String(text.getBytes("gb2312"));
- System.out.println("--"+text);
- }
- }
- }