package com.yc.schedule; import java.sql.SQLException; import java.util.ArrayList; import java.util.List; import java.util.Map; import java.util.Properties; import java.util.concurrent.Executor; import java.util.concurrent.Executors; import javax.mail.AuthenticationFailedException; import javax.mail.Authenticator; import javax.mail.Flags; import javax.mail.Folder; import javax.mail.Message; import javax.mail.MessagingException; import javax.mail.NoSuchProviderException; import javax.mail.Part; import javax.mail.PasswordAuthentication; import javax.mail.Session; import javax.mail.Store; import javax.mail.Flags.Flag; import javax.mail.internet.MimeMessage; import org.quartz.JobExecutionContext; import org.quartz.JobExecutionException; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.jdbc.CannotGetJdbcConnectionException; import org.springframework.scheduling.quartz.QuartzJobBean; import org.springframework.stereotype.Service; import com.sun.mail.pop3.POP3Folder; import com.sun.mail.pop3.POP3Message; import com.yc.action.mail.entity.MailAttachment; import com.yc.action.mail.entity.MailInfo; import com.yc.action.mail.entity.OneMail; import com.yc.action.mail.service.MailInfoIfc; import com.yc.action.mail.service.OtherMailIfc; import com.yc.entity.DataSourceEntity; import com.yc.factory.FactoryBean; import com.yc.factory.InitSystem; import com.yc.multiData.MultiDataSource; import com.yc.multiData.SpObserver; @Service public class EmailReceiverTimer extends QuartzJobBean { @Autowired private MailInfoIfc mailInfoIfc; @Autowired private OtherMailIfc otherMailIfc; @Override synchronized protected void executeInternal(JobExecutionContext context) throws JobExecutionException { // 创建一个可重用固定线程数的线程池,以共享的无界队列方式来运行这些线程。 Executor executor = Executors.newFixedThreadPool(10); otherMailIfc = (OtherMailIfc) context.getJobDetail().getJobDataMap().get("OtherMailImpl"); mailInfoIfc = (MailInfoIfc) context.getJobDetail().getJobDataMap().get("MailInfoImpl"); MultiDataSource multiDataSource = (MultiDataSource) FactoryBean.getBean("multiDataSource"); try { SpObserver.setDBtoDemo(); multiDataSource.refreshDataSource(null); } catch (SQLException e1) { System.out.println(e1.getMessage() + "[连接不到数据库,请检查数据源配置]"); e1.printStackTrace(); } finally { SpObserver.setDBtoInstance(); } Runnable task = new Runnable() { public void run() { String usercode = ""; String mailAttachSavePath = "";// 附件保存路径 Map infoList = MultiDataSource.getDataSourceMaps(); for (Map.Entry entry : infoList.entrySet()) { DataSourceEntity dataSourceEntity = entry.getValue(); try { SpObserver.setDBtoInstance("_" +dataSourceEntity.getDbId()); // System.out.println("数据库:"+map.get("db").toString()); List> usercodeList = new ArrayList>(); try { usercodeList = otherMailIfc.getUsercode(); } catch (CannotGetJdbcConnectionException ex) { System.out.println("请检查帐套 " + dataSourceEntity.getSystemID() + " 是否存在!"); usercodeList = null; continue; } List> otherMailList = new ArrayList>(); for (Map usercodeMap : usercodeList) { usercode = usercodeMap.get("usercode").toString(); mailAttachSavePath = InitSystem.getMailSavePath() + "\\" + usercodeMap.get("usercode").toString(); otherMailList = otherMailIfc.getMailInfoByUsercode(usercodeMap.get("usercode").toString()); for (int j = 0; j < otherMailList.size(); j++) { final String username = otherMailList.get(j).get("mailAddress").toString(); final String password = otherMailList.get(j).get("password").toString(); // 创建Properties 对象 Properties props = new Properties(); // 创建邮件会话 Session mailSession = Session.getDefaultInstance(props, new Authenticator() { @Override public PasswordAuthentication getPasswordAuthentication() { return new PasswordAuthentication(username, password); // return new PasswordAuthentication("lqc_fs@163.com", "qc722268"); } }); // Session mailSession = Session.getDefaultInstance(new Properties(),null); // URLName urlName = new URLName("pop3",pop3host,port, null,username, password); Store store; try { store = mailSession.getStore("pop3"); // System.out.println("begin store connect..."); // System.out.println(store); // store.connect(pop3host,username, password); // store.connect("pop.163.com","lqc_fs@163.com", "qc722268"); store.connect(otherMailList.get(j).get("pop3").toString(), otherMailList.get(j).get("mailAddress").toString(), otherMailList.get(j).get("password").toString()); // System.out.println(store); // System.out.println("end store connect..."); Folder folder = store.getFolder("INBOX"); POP3Folder inbox = (POP3Folder) folder; folder.open(Folder.READ_WRITE); // SearchTerm st = new FlagTerm( // new Flags(Flags.Flag.SEEN), false); // // Message [] messages = folder.search(st); Message[] messages = folder.getMessages(); MailInfo mailInfo = null; List attas = null; for (int i = 0; i < messages.length; i++) { // 读取数据库中是否存在这样的UID,如何存在,跳过,如果不存在,读取,并在UID表中插入一条记录,通过数据库的一个UID表来实现存储和判断。 MimeMessage mimeMessage = (MimeMessage) messages[i]; String uid = inbox.getUID(mimeMessage);// 过滤已经下载过的邮件,而不用重复下载 利用邮件唯一的uid来实现,邮件服务器上的每一个邮件都有一个唯一标识 UID ((POP3Message) messages[i]).invalidate(true); OneMail mail = new OneMail((MimeMessage) messages[i]); mail.getMailContent((Part) messages[i]); mail.setAttachPath(mailAttachSavePath); mail.setXianduiPath("/WEB-INF/MAIL/" + usercode); mailInfo = new MailInfo(i, mail.getMessageId(), usercode, "inbox", mail.getFrom(), mail.getMailAddress("TO"), mail.getMailAddress("CC"), mail.getMailAddress("BCC"), mail.getSubject(), mail.getBodyText(), 0, mail.getReplySign() ? 1 : 0, mail.getSentDate()); // ----------lqc-------- mailInfo.setUid(uid); mailInfo.setOtherMailAddress(otherMailList.get(j).get("mailAddress").toString()); Flags flags = messages[i].getFlags(); // if(!flags.contains(Flags.Flag.SEEN))//未读 List> list = mailInfoIfc.getMialInfoUid(usercode, "inbox"); int index = 0; for (Map map2 : list) { if (map2.get("uid") != null && map2.get("uid").toString().equals(uid)) { index = 1; break; } } if (index == 0 && !flags.contains(Flags.Flag.SEEN)) mailInfoIfc.addMail(mailInfo);// 过滤已经下载过的邮件,而不用重复下载 利用邮件唯一的uid来实现 // -----------end----------- if (mail.isContainAttach((Part) messages[i])) { attas = new ArrayList(); mail.saveAttachMent((MimeMessage) messages[i], usercode, attas); for (MailAttachment myentry : attas) { mailInfoIfc.addMailAttachPath(myentry); } } // mail.deleteMail(); if (otherMailList.get(j).get("isRetain").toString().equals("0")) { messages[i].setFlag(Flag.DELETED, true); } } folder.close(true); store.close(); } catch (AuthenticationFailedException e) { e.printStackTrace(); // out.write("{'code':'error','info':'身份验证失败!'}"); } catch (NoSuchProviderException e) { e.printStackTrace(); } catch (MessagingException e) { e.printStackTrace(); } catch (Exception e) { e.printStackTrace(); } } } } catch (Exception e) { e.printStackTrace(); } finally { SpObserver.setDBtoInstance(); } } } }; // 使用Executor框架的线程池执行邮件发送任务 executor.execute(task); } }