xinyb
3 天以前 3b74e3df72726e188d36393ecfd7964d095ef7e8
提交 | 用户 | age
18553a 1 package com.yc.crm.schedule;
F 2
3 import com.sun.mail.imap.IMAPFolder;
4 import com.sun.mail.imap.IMAPStore;
5 import com.yc.api.schedule.ScheduleUtils;
6 import com.yc.crm.mail.entity.FoundationEntity;
7 import com.yc.crm.mail.entity.T482102Entity;
8 import com.yc.crm.mail.service.MailAccountIfc;
9 import com.yc.crm.mail.service.MailServiceIfc;
10 import com.yc.entity.AttachmentConfig;
11 import com.yc.entity.DataSourceEntity;
12 import com.yc.factory.FactoryBean;
13 import com.yc.multiData.MultiDataSource;
14 import com.yc.multiData.SpObserver;
15 import lombok.extern.slf4j.Slf4j;
16 import org.springframework.beans.factory.annotation.Autowired;
17 import org.springframework.context.ApplicationListener;
18 import org.springframework.context.event.ContextRefreshedEvent;
19 import org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor;
20 import org.springframework.scheduling.concurrent.ThreadPoolTaskScheduler;
21 import org.springframework.stereotype.Service;
22
23 import javax.mail.*;
24 import javax.mail.event.MessageCountEvent;
25 import javax.mail.event.MessageCountListener;
26 import java.util.HashMap;
27 import java.util.List;
28 import java.util.Map;
29 import java.util.Properties;
30
31 /**
32  * 实时监听邮箱
33  */
34 @Slf4j
35 @Service
36 public class EmailSchedule implements ApplicationListener<ContextRefreshedEvent> {
37     @Autowired
38     ThreadPoolTaskExecutor threadPoolExecutor;
39     @Autowired
40     private ThreadPoolTaskScheduler threadPoolTaskScheduler;
41     @Autowired
42     MailAccountIfc emailAccountIfc;
43     @Autowired
44     MailServiceIfc mailServiceIfc;
45
46     @Override
47     public void onApplicationEvent(ContextRefreshedEvent contextRefreshedEvent) {
48         if (contextRefreshedEvent.getApplicationContext().getParent() == null) {
49             return;
50         }
51         threadPoolTaskScheduler = (ThreadPoolTaskScheduler) FactoryBean.getBean("threadPoolTaskScheduler");
52         threadPoolExecutor = (ThreadPoolTaskExecutor) FactoryBean.getBean("threadPoolExecutor");
53         String isStartUpSchedule = AttachmentConfig.get("isStartUpSchedule");//只在设置了定时任务的服务器上运行
54         if ("1".equals(isStartUpSchedule)) {
55             Map<String, DataSourceEntity> infoList = MultiDataSource.getDataSourceMaps();
56             for (Map.Entry<String, DataSourceEntity> entry : infoList.entrySet()) {
57                 DataSourceEntity dataSourceEntity = entry.getValue();
58                 if (ScheduleUtils.isOnbusPlatform(dataSourceEntity) || dataSourceEntity.getDbId() == 1624) {
59                     //dbid=1624,巴士软件(佛山公司),不需要执行定时任务
60                     continue;
61                 }
62           // if (dataSourceEntity.getDbId() != 82) continue;//TODO 测试用
63                emailTask(dataSourceEntity);
64             }
65         }
66     }
67
68     private void emailTask(DataSourceEntity dataSourceEntity) {
69             try {
70                 SpObserver.setDBtoInstance("_" + dataSourceEntity.getDbId());
71                 List<T482102Entity> list = emailAccountIfc.getAccountList();
72                 log.info(dataSourceEntity.getDbId()+"-加载邮箱数量:"+list.size());
73                 for (T482102Entity t482102Entity : list) {
74                         threadPoolExecutor.execute(new checkEmailThread(t482102Entity,dataSourceEntity));
75                 }
76             } catch (Exception e) {
77                 System.out.println("取不到邮箱设置内容:dbid=" + dataSourceEntity.getDbId() + ":" + e.getMessage());
78                 e.printStackTrace();
79             } finally {
80                 SpObserver.setDBtoInstance();
81             }
82         }
83
84     private class checkEmailThread implements Runnable {
85         T482102Entity emailEntity;
86         FoundationEntity foundation;
87         DataSourceEntity dataSourceEntity;
88         public checkEmailThread(T482102Entity t482102Entity, DataSourceEntity dataSourceEntity) {
89             this.emailEntity = t482102Entity;
90             this.dataSourceEntity = dataSourceEntity;
91             foundation=new FoundationEntity();
92             foundation.setDbId(dataSourceEntity.getDbId());
93             foundation.setCompanyName(emailEntity.getCompanyName());
94             foundation.setCompanyId(emailEntity.getCompanyId());
95             foundation.setUserCode(emailEntity.getUserCode());
96             foundation.setUserName(emailEntity.getUserName());
97         }
98
99         @Override
100         public void run() {
101             checkEmail();
102     }
103     private void checkEmail() {
104         try {
105             String protocol = emailEntity.getReceiveProtocol().toLowerCase();//接收协议 imap pop3
106             String server = emailEntity.getReceiveHost();//"imap.qq.com";
107             Integer port = emailEntity.getReceivePort();//993
108             String user =emailEntity.getReceiveEmail();//邮箱
109             String pwd = emailEntity.getReceivePassword();//密码
110             Properties properties = new Properties();
111             properties.setProperty("mail.store.protocol", protocol); // IMAP over SSL
112             if (protocol.contains("imap")) {//接收协议imap
113                 properties.setProperty("mail.imaps.host", server);
114                 properties.setProperty("mail.imaps.port", port + "");
115             } else if (protocol.contains("pop3")) {//接收协议pop3
116                 properties.setProperty("mail.pop3.host", server);
117                 properties.setProperty("mail.pop3.port", port + "");
118             } else {//其他(再加)
119                 properties.setProperty("mail.imaps.host", server);
120                 properties.setProperty("mail.imaps.port", port + "");
121             }
122             HashMap IAM = new HashMap();
123             //带上IMAP ID信息,由key和value组成,例如name,version,vendor,support-email等。
124             IAM.put("name", user);
125             IAM.put("version", emailEntity.getDocVersion() + "");
126             IAM.put("vendor", emailEntity.getCompanyName());
127             IAM.put("support-email", emailEntity.getEmail());
128             //创建会话
129             Session session = Session.getInstance(properties, new Authenticator() {
130                 @Override
131                 protected PasswordAuthentication getPasswordAuthentication() {
132                     return new PasswordAuthentication(user, pwd);
133                 }
134             });
135             //存储对象
136             IMAPStore store = (IMAPStore) session.getStore(protocol);//imap协议或pop3协议类型(推荐你使用IMAP协议来存取服务器上的邮件。)
137             //连接
138             store.connect(server, user, pwd);
139             store.id(IAM);//163邮箱需要,不然会报:A3 NO SELECT Unsafe Login. Please contact kefu@188.com for help
140             Folder folder = null;
141             try {
142                 // 获得收件箱
143                 folder = store.getFolder("INBOX");
144                 // 以读写模式打开收件箱
145                 folder.open(Folder.READ_WRITE);
146                 log.info(emailEntity.getEmail() + "已就绪接收新邮件....");
147                 folder.addMessageCountListener(new MessageCountListener() {
148                     @Override
149                     public void messagesAdded(MessageCountEvent e) {
150                         //TODO 处理新邮件
151                         try {
152                             SpObserver.setDBtoInstance("_" + dataSourceEntity.getDbId());
3b74e3 153                             mailServiceIfc.setMailContent(e.getMessages(), emailEntity, foundation,true);
18553a 154                         }catch (Exception e1){
F 155                             e1.printStackTrace();
156                         }finally {
157                             SpObserver.setDBtoInstance();
158                         }
159                         log.info(emailEntity.getEmail()+":Message Count Event Fired");
160                     }
161                     @Override
162                     public void messagesRemoved(MessageCountEvent e) {
163                        // System.out.println(emailEntity.getEmail()+"Message Count Event Fired");
164                     }
165                 });
166
167                /* folder.addMessageChangedListener(new MessageChangedListener() {
168                     @Override
169                     public void messageChanged(MessageChangedEvent e) {
170                         System.out.println(emailEntity.getEmail()+"Message Count Event Fired");
171                     }
172                 });*/
173                 // Check mail once in "freq" MILLIseconds
174                 int freq = 2000;
175                 boolean supportsIdle = false;
176                 try {
177                     if (folder instanceof IMAPFolder) {
178                         IMAPFolder f = (IMAPFolder) folder;
179                         f.idle();
180                         supportsIdle = true;
181                     }
182                 } catch (FolderClosedException fex) {
183                     throw fex;
184                 } catch (MessagingException mex) {
185                     supportsIdle = false;
186                 }
187                 for (; ; ) {
188                     if (supportsIdle && folder instanceof IMAPFolder) {
189                         IMAPFolder f = (IMAPFolder) folder;
190                         f.idle();
191                        // System.out.println(emailEntity.getEmail()+"IDLE done");
192                     } else {
193                         Thread.sleep(freq); // sleep for freq milliseconds
194                         // This is to force the IMAP server to send us
195                         // EXISTS notifications.
196                         folder.getMessageCount();
197                     }
198                 }
199
200             } catch (FolderClosedException fe) {
201                 log.info("FolderClosedException......");
202                 checkEmail();
203
204             } catch (Exception e) {
205                 throw new RuntimeException(e);
206             } finally {
207                 try {
208                     if (folder != null) {
209                         folder.close(false);
210                     }
211                     if (store != null) {
212                         store.close();
213                     }
214                 } catch (MessagingException e) {
215                     throw e;
216                 }
217             }
218         }catch (Exception e){
219             e.printStackTrace();
220         }
221     }
222 }
223 }