658898d28cded745ca15ee0a89e3025358356259..b7ef4bb09e69ba27c29ea06a7f348f753c530a44
9 天以前 xinyb
CRM邮箱配置调整
b7ef4b 对比 | 目录
9 天以前 fs-danaus
更新CRM新邮件通知代码
18553a 对比 | 目录
2个文件已添加
21个文件已修改
715 ■■■■■ 已修改文件
src/com/yc/crm/base/service/CrmServiceImpl.java 14 ●●●● 补丁 | 查看 | 原始文档 | blame | 历史
src/com/yc/crm/clues/service/CluesServiceImpl.java 26 ●●●● 补丁 | 查看 | 原始文档 | blame | 历史
src/com/yc/crm/mail/action/MailDemo.java 148 ●●●●● 补丁 | 查看 | 原始文档 | blame | 历史
src/com/yc/crm/mail/action/MailFolder.java 38 ●●●●● 补丁 | 查看 | 原始文档 | blame | 历史
src/com/yc/crm/mail/action/MailPush.java 63 ●●●●● 补丁 | 查看 | 原始文档 | blame | 历史
src/com/yc/crm/mail/action/MailTag.java 45 ●●●●● 补丁 | 查看 | 原始文档 | blame | 历史
src/com/yc/crm/mail/entity/FoundationEntity.java 2 ●●●●● 补丁 | 查看 | 原始文档 | blame | 历史
src/com/yc/crm/mail/entity/MailModuleBelowEntity.java 1 ●●●● 补丁 | 查看 | 原始文档 | blame | 历史
src/com/yc/crm/mail/service/MailAccountIfc.java 6 ●●●●● 补丁 | 查看 | 原始文档 | blame | 历史
src/com/yc/crm/mail/service/MailAccountImpl.java 28 ●●●● 补丁 | 查看 | 原始文档 | blame | 历史
src/com/yc/crm/mail/service/MailFolderIfc.java 2 ●●● 补丁 | 查看 | 原始文档 | blame | 历史
src/com/yc/crm/mail/service/MailFolderImpl.java 9 ●●●●● 补丁 | 查看 | 原始文档 | blame | 历史
src/com/yc/crm/mail/service/MailIfc.java 2 ●●● 补丁 | 查看 | 原始文档 | blame | 历史
src/com/yc/crm/mail/service/MailImpl.java 38 ●●●●● 补丁 | 查看 | 原始文档 | blame | 历史
src/com/yc/crm/mail/service/MailServiceIfc.java 9 ●●●●● 补丁 | 查看 | 原始文档 | blame | 历史
src/com/yc/crm/mail/service/MailServiceImpl.java 25 ●●●● 补丁 | 查看 | 原始文档 | blame | 历史
src/com/yc/crm/mail/service/MailTagImpl.java 2 ●●●●● 补丁 | 查看 | 原始文档 | blame | 历史
src/com/yc/crm/schedule/EmailSchedule.java 224 ●●●●● 补丁 | 查看 | 原始文档 | blame | 历史
src/com/yc/crm/schedule/MessagePopSchedule.java 13 ●●●● 补丁 | 查看 | 原始文档 | blame | 历史
src/com/yc/open/baiwang/controller/BaiwangController.java 2 ●●● 补丁 | 查看 | 原始文档 | blame | 历史
src/com/yc/open/baiwang/schedule/QueryThread.java 11 ●●●●● 补丁 | 查看 | 原始文档 | blame | 历史
src/com/yc/open/baiwang/service/BaiwangIfc.java 3 ●●●● 补丁 | 查看 | 原始文档 | blame | 历史
src/com/yc/open/baiwang/service/BaiwangImpl.java 4 ●●● 补丁 | 查看 | 原始文档 | blame | 历史
src/com/yc/crm/base/service/CrmServiceImpl.java
@@ -525,6 +525,14 @@
            if (StringUtils.isBlank(entity.getRepeatEnd())) {
                throw new ApplicationException("周期性结束日期不能为空");
            }
            if(entity.getFullDayFlag()==1){
                //表示不需要时间,只有日期
                entity.setStartTime(entity.getStartTime().trim().split("\\s+")[0]);
                entity.setEndTime(entity.getEndTime().trim().split("\\s+")[0]);
                if(StringUtils.isNotBlank(entity.getRepeatEnd())) {
                    entity.setRepeatEnd(entity.getRepeatEnd().trim().split("\\s+")[0]);
                }
            }
            if (entity.getId() == null || entity.getId() == 0) {//新增
                calRepeatDate(entity, list);
            } else if (entity.getId() != null && entity.getId() != 0 && entity.getRepeatFlag() == 1) {//修改且选择了生成后续重复日程
@@ -551,17 +559,17 @@
        } catch (Exception e) {
            //表示没有时间,需要增加00:00:00才不出错
            start = LocalDateTime.parse(entity.getStartTime() + " 00:00:00", DateTimeFormatter.ofPattern(pattern));
            start = LocalDateTime.parse(entity.getStartTime() + " 09:00:00", DateTimeFormatter.ofPattern(pattern));
        }
        try {
            end = LocalDateTime.parse(entity.getEndTime(), DateTimeFormatter.ofPattern(pattern));
        } catch (Exception e) {
            end = LocalDateTime.parse(entity.getEndTime() + " 00:00:00", DateTimeFormatter.ofPattern(pattern));
            end = LocalDateTime.parse(entity.getEndTime() + " 09:00:00", DateTimeFormatter.ofPattern(pattern));
        }
        try {
            repeatEnd = LocalDateTime.parse(entity.getRepeatEnd(), DateTimeFormatter.ofPattern(pattern));
        } catch (Exception e) {
            repeatEnd = LocalDateTime.parse(entity.getRepeatEnd() + " 00:00:00", DateTimeFormatter.ofPattern(pattern));
            repeatEnd = LocalDateTime.parse(entity.getRepeatEnd() + " 09:00:00", DateTimeFormatter.ofPattern(pattern));
        }
        calStart.setTime(Date.from(start.atZone(ZoneId.systemDefault()).toInstant()));
        //结束日期取周期性设置
src/com/yc/crm/clues/service/CluesServiceImpl.java
@@ -63,7 +63,7 @@
                "    @Address                  varchar(200),\n" +
                "    @PostCode                 varchar(50),\n" +
                "    @HDMemo                   varchar(500),\n" +
                "    @clues_name               nvarchar(50),\n" +
                "    @clues_name               nvarchar(250),\n" +
                "    @last_edit_user           varchar(20),\n" +
                "    @edit_time                datetime,\n" +
                "    @public_time              datetime,\n" +
@@ -670,22 +670,35 @@
    @Transactional(rollbackFor = Exception.class)
    @Override
    public void newAssign(AssignCluesEntity assignClues) {
        //推送规则:
        // 1,系统预设个人跟进线索,客户的最大数
        //2,根据业务员的级别优先推送,影响级别的因素有:业务员业绩金额(历史业绩)、畅销品(可以匹配到公司畅销品)、新人业务员(如何定义为新人?入职时间,成交数)、客户的国家、业务员优势(外语,耐心)等。(新人业务员一般会分配畅销品)
        //由这些维度优先级进行推送给业务员
        if(StringUtils.isBlank(assignClues.getOwnerCode())&&StringUtils.isBlank(assignClues.getOwnerCcCode())){
            throw new ApplicationException("部门和用户不能都为空");
        }
        String sql = " declare @refCode varchar(20),@ownerCode varchar(20),@ownerName varchar(20)\n" +
                " ,@ownerCcCode varchar(20),@ownerCcName varchar(20),@ownerType int=0" +
                " ,@ownerCcCode varchar(20),@ownerCcName varchar(20),@ownerType int=0 \n" +
                "select @refCode=" + GridUtils.prossSqlParm(assignClues.getDocCode()) + ",@ownerCode=" + GridUtils.prossSqlParm(assignClues.getOwnerCode()) + ",@ownerName=" + GridUtils.prossSqlParm(assignClues.getOwnerName()) + ",@ownerCcCode=" + GridUtils.prossSqlParm(assignClues.getOwnerCcCode()) + ",@ownerCcName=" + GridUtils.prossSqlParm(assignClues.getOwnerCcName()) + "\n";
        if(StringUtils.isNotBlank(assignClues.getOwnerCcCode())) {
        if(StringUtils.isNotBlank(assignClues.getOwnerCode())) {
            sql+=" select @ownerType=1 \n";//表示当前线索是分配到个人,而不是部门
        }
                sql+=" insert into t481104h(refCode          \n" +
                sql+=" declare @num int=0\n" +
                        " select @num=count(1) from t481101h where isnull(ispush,0)=1 \n" +
                        "if @num=1 \n" +
                        "begin\n" +
                        " raiserror('当前线索已分配,不能再分配',16,1)\n" +
                        " return\n" +
                        "end\n" +
                        "insert into t481104h(refCode          \n" +
                ",ownerCode        \n" +
                ",ownerName        \n" +
                ",ownerCcCode        \n" +
                ",ownerCcName        \n" +
                ",ownerType       \n" +
                ",enterTime       \n)values(@refCode,@ownerCode,@ownerName,@ownerType,getdate())";
                ",enterTime       \n)values(@refCode,@ownerCode,@ownerName,@ownerCcCode,@ownerCcName,@ownerType,getdate())\n" +
                        " update t481101h set isPush=1 where doccode=@refCode\n";
        this.doBaseExecute(sql);
    }
@@ -699,7 +712,8 @@
                " insert into t481104h(refCode          \n" +
                ",ownerCode        \n" +
                ",ownerName        \n" +
                ",enterTime       \n)values(@refCode,@ownerCode,@ownerName,getdate())";
                ",ownerType        \n" +
                ",enterTime       \n)values(@refCode,@ownerCode,@ownerName,1,getdate())";
        this.doBaseExecute(sql);
    }
src/com/yc/crm/mail/action/MailDemo.java
@@ -1,10 +1,15 @@
package com.yc.crm.mail.action;
import com.sun.mail.imap.IMAPFolder;
import com.sun.mail.imap.IMAPStore;
import org.springframework.mail.SimpleMailMessage;
import org.springframework.mail.javamail.JavaMailSenderImpl;
import javax.mail.*;
import javax.mail.event.MessageChangedEvent;
import javax.mail.event.MessageChangedListener;
import javax.mail.event.MessageCountEvent;
import javax.mail.event.MessageCountListener;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeUtility;
import javax.mail.search.FlagTerm;
@@ -18,23 +23,152 @@
        mailSender.setHost("smtp.163.com");//邮箱服务商
        mailSender.setProtocol("smtp");//发邮件
        mailSender.setUsername("xxxxx@163.com");//账号
        mailSender.setPassword("Xxxx");//授权码
        mailSender.setPassword("Xxxxxx");//授权码
        mailSender.setDefaultEncoding("utf-8");
        SimpleMailMessage message = new SimpleMailMessage();
        message.setTo("xxxxx@qq.com");
        message.setTo("xxxx@qq.com");
        message.setSubject("测试邮箱");
        message.setText("abc");
        message.setFrom("xxxxx@163.com");//发件人邮箱
        message.setFrom("xxxxx@qq.com");//发件人邮箱
        mailSender.send(message);
    }
    public static void main(String[] args) throws Exception {
        ReceiveEmail();
       //ReceiveEmail();
        checkEmail();
    }
    public static void checkEmail() {
        try {
            String protocol = "imaps";//emailEntity.getReceiveProtocol().toLowerCase();//接收协议 imap pop3
            String server = "imap.qq.com";//emailEntity.getReceiveHost();//"imap.qq.com";
            Integer port =993;// emailEntity.getReceivePort();//993
            String user = "xxxx@qq.com";//邮箱
            String pwd ="xxxxxxxx";//密码
            Properties properties = new Properties();
            properties.setProperty("mail.store.protocol", protocol); // IMAP over SSL
            if (protocol.contains("imap")) {//接收协议imap
                properties.setProperty("mail.imaps.host", server);
                properties.setProperty("mail.imaps.port", port + "");
            } else if (protocol.contains("pop3")) {//接收协议pop3
                properties.setProperty("mail.pop3.host", server);
                properties.setProperty("mail.pop3.port", port + "");
            } else {//其他(再加)
                properties.setProperty("mail.imaps.host", server);
                properties.setProperty("mail.imaps.port", port + "");
            }
       //properties.put("mail.imaps.starttls.enable", "true");//// IMAP 协议设置 STARTTLS
            HashMap IAM = new HashMap();
            //带上IMAP ID信息,由key和value组成,例如name,version,vendor,support-email等。
            IAM.put("name","myname");
            IAM.put("version","1.0.0");
            IAM.put("vendor","myclient");
            IAM.put("support-email","testmail@test.com");
            //创建会话
            Session session = Session.getInstance(properties, new Authenticator() {
                @Override
                protected PasswordAuthentication getPasswordAuthentication() {
                    return new PasswordAuthentication(user, pwd);
                }
            });
            //存储对象
            IMAPStore store = (IMAPStore) session.getStore(protocol);//imap协议或pop3协议类型(推荐你使用IMAP协议来存取服务器上的邮件。)
            //连接
            store.connect(server, user, pwd);
            store.id(IAM);//163邮箱需要,不然会报:A3 NO SELECT Unsafe Login. Please contact kefu@188.com for help
            Folder folder = null;
            try {
                // 获得收件箱
                folder = store.getFolder("INBOX");
                // 以读写模式打开收件箱
                folder.open(Folder.READ_WRITE);
                folder.addMessageCountListener(new MessageCountListener() {
                    @Override
                    public void messagesAdded(MessageCountEvent e) {
                        try {
                            Message[] messages = e.getMessages();
                            for (int i = 0; i < messages.length; i++) {
                                System.out.println("消息:" + messages[i].getSubject());
                                System.out.println("内容:" + messages[i].getContent());
                                String from = MimeUtility.decodeText(messages[i].getFrom()[0].toString());
                                InternetAddress internetAddress = new InternetAddress(from);
                                System.out.println("发件人:" + internetAddress.getPersonal() + '(' + internetAddress.getAddress() + ')');
                            }
                            System.out.println("Message Count Event Fired");
                        }catch (Exception ex){
                            ex.printStackTrace();
                        }
                    }
                    @Override
                    public void messagesRemoved(MessageCountEvent e) {
                        System.out.println("Message Count Event Fired");
                    }
                });
                folder.addMessageChangedListener(new MessageChangedListener() {
                    @Override
                    public void messageChanged(MessageChangedEvent e) {
                        System.out.println("Message Count Event Fired");
                    }
                });
                // Check mail once in "freq" MILLIseconds
                int freq = 5000;
                boolean supportsIdle = false;
                try {
                    if (folder instanceof IMAPFolder) {
                        IMAPFolder f = (IMAPFolder) folder;
                        f.idle();
                        supportsIdle = true;
                    }
                } catch (FolderClosedException fex) {
                    checkEmail();
                    throw fex;
                } catch (MessagingException mex) {
                    supportsIdle = false;
                }
                for (; ; ) {
                    System.out.println("run......");
                    if (supportsIdle && folder instanceof IMAPFolder) {
                        IMAPFolder f = (IMAPFolder) folder;
                        f.idle();
                        System.out.println("IDLE done");
                    } else {
                        Thread.sleep(freq); // sleep for freq milliseconds
                        System.out.println("sleep start......");
                        // This is to force the IMAP server to send us
                        // EXISTS notifications.
                        int messageCount = folder.getNewMessageCount();
                        System.out.println("messageCount......"+messageCount);
                    }
                }
            } catch (FolderClosedException fe) {
                System.out.println("FolderClosedException......");
                checkEmail();
            }
            catch (Exception e) {
                throw new RuntimeException(e);
            } finally {
                try {
                    if (folder != null) {
                        folder.close(false);
                    }
                    if (store != null) {
                        store.close();
                    }
                } catch (MessagingException e) {
                    throw e;
                }
            }
        }catch (Exception e){
            e.printStackTrace();
        }
    }
    public static  void ReceiveEmail() throws MessagingException, IOException {
        String imapServer = "imap.qq.com";
        String user="xxx@qq.com";
        String pwd="xxxx";
        String user = "xxxxx@qq.com";//邮箱
        String pwd ="xxxxx";//密码
        HashMap IAM = new HashMap();
//带上IMAP ID信息,由key和value组成,例如name,version,vendor,support-email等。
@@ -50,7 +184,7 @@
            }
        });
        //存储对象
        IMAPStore store = (IMAPStore) session.getStore("imap");
        IMAPStore store = (IMAPStore) session.getStore("imaps");
        //连接
        store.connect(imapServer,user,pwd);
        store.id(IAM);//163邮箱需要,不然会报:A3 NO SELECT Unsafe Login. Please contact kefu@188.com for help
src/com/yc/crm/mail/action/MailFolder.java
@@ -1,6 +1,7 @@
package com.yc.crm.mail.action;
import com.yc.crm.mail.entity.FolderEntity;
import com.yc.crm.mail.entity.MailModuleBelowEntity;
import com.yc.crm.mail.entity.T482107Entity;
import com.yc.crm.mail.service.MailFolderIfc;
import com.yc.crm.mail.util.AllBackMsg;
@@ -161,7 +162,7 @@
     * @return
     */
    @GetMapping("/getFolder.do")
    public AllBackMsg getFolder(String search, HttpServletRequest request, HttpServletResponse response) {
    public AllBackMsg getFolder(HttpServletRequest request, HttpServletResponse response) {
        AllBackMsg msg = new AllBackMsg();
        try {
            HttpSession session = request.getSession();
@@ -172,7 +173,7 @@
            }
            DataSourceEntity dataSource = MultiDataSource.getDataSourceMap(request);//获取数据源
            SpObserver.setDBtoInstance("_" + dataSource.getDbId());
            List<T482107Entity> t482107Entities = mailFolderIfc.getMailFolder(userCode, search);
            List<T482107Entity> t482107Entities = mailFolderIfc.getMailFolder(userCode);
            if (t482107Entities.size() > 0) {
                //返回树结构
                msg.setSuccess("执行成功", getFolderList(t482107Entities, ""));
@@ -217,4 +218,37 @@
            throw e;
        }
    }
    /**
     * 文件夹树结构
     *
     * @param t482107
     * @param rowId
     * @return
     */
    public static List<MailModuleBelowEntity> getFolderModule(List<T482107Entity> t482107, String rowId) {
        List<MailModuleBelowEntity> folder = new ArrayList<>();
        try {
            for (T482107Entity t : t482107) {
                if (folder.stream().filter(f -> f.getParentKey().equals(rowId)).count() == 0) {
                    List<T482107Entity> fo = t482107.stream().filter(o -> o.getParentRowId().equals(rowId)).collect(Collectors.toList());
                    if (fo.size() > 0) {
                        for (T482107Entity y : fo) {
                            MailModuleBelowEntity folder1 = new MailModuleBelowEntity();
                            folder1.setKey(y.getRowId());
                            folder1.setParentKey(y.getParentRowId());
                            folder1.setName(y.getFolderName());
                            folder1.setList(getFolderModule(t482107, y.getRowId()));
                            folder.add(folder1);
                        }
                    } else {
                        break;
                    }
                }
            }
            return folder;
        } catch (Exception e) {
            throw e;
        }
    }
}
src/com/yc/crm/mail/action/MailPush.java
New file
@@ -0,0 +1,63 @@
package com.yc.crm.mail.action;
import cn.jiguang.common.resp.APIConnectionException;
import cn.jiguang.common.resp.APIRequestException;
import com.yc.api.utils.PushMessageType;
import com.yc.crm.mail.entity.t482101HEntity;
import com.yc.ionic.schedule.JpushMsg;
import com.yc.jpush.JpushAction;
import lombok.SneakyThrows;
import org.springframework.stereotype.Component;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
/**
 * 推送新邮件通知
 */
@Component
public class MailPush {
    private static JpushAction jpushAction =JpushAction.getInstance();
    @SneakyThrows
    public  static  void pushEmailInfo(List<t482101HEntity> list, String docCodeList, int dbid, String telephone){
        String[] docCodes = docCodeList.split(";");
        int index=0;
        for (t482101HEntity entity: list) {
            Map<String, String> extras = new HashMap<>();
            extras.put("actionType", "crm_email");
            extras.put("msg", entity.getSubject());
            extras.put("msgCount", "1");
            extras.put("docCode", docCodes[index]);
            extras.put("userCode", entity.getUserCode());
            extras.put("tel", telephone);
            extras.put("dbid", dbid + "");
            extras.put("title", "邮件提醒");
            List<String> alais = new ArrayList<String>();
            alais.add(telephone);
            JpushMsg msg = new JpushMsg(alais, entity.getSubject(), extras, dbid, "", "", docCodes[index]);
            try {
                boolean push = jpushAction.sendPush(
                        JpushAction.buildPushObject_with_extra(
                                msg.getAlais(), msg.getTopic(), msg.getExtras())
                );
                //System.out.println("push:"+push);
            }catch (APIConnectionException e) {
                // Connection error, should retry later
                System.out.println(" Connection error, should retry later" + e.getMessage());
            } catch (APIRequestException e) {
                // Should review the error, and fix the request
                System.out.println("dbid: " + dbid);
                System.out.println("HTTP Status: " + e.getStatus());
                System.out.println("Error Code: " + e.getErrorCode());
                System.out.println("Error Message: " + e.getErrorMessage());
            } catch (Exception e) {
                System.out.println(">推送出错:" + e.getMessage());
                e.printStackTrace();
            }
            index++;
        }
    }
}
src/com/yc/crm/mail/action/MailTag.java
@@ -3,6 +3,7 @@
//import com.yc.crm.mail.entity.T482115Entity;
import com.yc.crm.base.entity.T482115Entity;
import com.yc.crm.mail.entity.MailModuleBelowEntity;
import com.yc.crm.mail.service.MailTagIfc;
import com.yc.crm.mail.util.AllBackMsg;
import com.yc.entity.DataSourceEntity;
@@ -16,6 +17,7 @@
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.util.ArrayList;
import java.util.List;
/**
@@ -147,7 +149,7 @@
     * @return
     */
    @GetMapping("/getTagList.do")
    public AllBackMsg getTagList(String search,@RequestParam(defaultValue = "-1") Integer type, HttpServletRequest request, HttpServletResponse response) {
    public AllBackMsg getTagList(String search, @RequestParam(defaultValue = "-1") Integer type, HttpServletRequest request, HttpServletResponse response) {
        AllBackMsg msg = new AllBackMsg();
        try {
            HttpSession session = request.getSession();
@@ -158,7 +160,7 @@
            }
            DataSourceEntity dataSource = MultiDataSource.getDataSourceMap(request);//获取数据源
            SpObserver.setDBtoInstance("_" + dataSource.getDbId());
            List<T482115Entity> list = mailTagIfc.getTagList(userCode, search,type);
            List<T482115Entity> list = mailTagIfc.getTagList(userCode, search, type);
            msg.setSuccess("执行成功", list);
        } catch (Exception e) {
            msg.setFail(e.getCause() != null ? e.getCause().getMessage() : e.getMessage());
@@ -167,4 +169,43 @@
        }
        return msg;
    }
    /**
     * 标签树结构
     *
     * @param t482107
     * @param rowId
     * @return
     */
    public static List<MailModuleBelowEntity> getTagModule(List<T482115Entity> T482115) {
        List<MailModuleBelowEntity> tagList = new ArrayList<>();
        MailModuleBelowEntity tag1 = new MailModuleBelowEntity();
        tag1.setKey("systemTag");
        tag1.setName("系统标签");
        MailModuleBelowEntity tag2 = new MailModuleBelowEntity();
        tag2.setKey("customTag");
        tag2.setName("自定义标签");
        try {
            List<MailModuleBelowEntity> system = new ArrayList<>();
            List<MailModuleBelowEntity> custom = new ArrayList<>();
            for (T482115Entity t : T482115) {
                MailModuleBelowEntity tag = new MailModuleBelowEntity();
                tag.setName(t.getTagName());
                if (t.isSystemFlag()) {
                    tag.setKey("systemTag" + t.getTagId());
                    system.add(tag);
                } else {
                    tag.setKey("customTag" + t.getTagId());
                    custom.add(tag);
                }
            }
            tag1.setList(system);
            tag2.setList(custom);
            tagList.add(tag1);
            tagList.add(tag2);
            return tagList;
        } catch (Exception e) {
            throw e;
        }
    }
}
src/com/yc/crm/mail/entity/FoundationEntity.java
@@ -30,5 +30,7 @@
        this.companyId = (String) session.getAttribute(SessionKey.COMPANY_ID);
        this.companyName = (String) session.getAttribute(SessionKey.COMPANY_NAME);
    }
public FoundationEntity(){
}
}
src/com/yc/crm/mail/entity/MailModuleBelowEntity.java
@@ -15,6 +15,7 @@
@Data
public class MailModuleBelowEntity {
    private String key;//key
    private String parentKey;//父key
    private String name;//名称
    private Integer number = 0;//数量
    private Object list;//下节点
src/com/yc/crm/mail/service/MailAccountIfc.java
@@ -64,4 +64,10 @@
    abstract T482102Entity getAccountInfo(String userCode, Integer accountId) throws Exception;
    abstract T482102Entity getAccountInfo(String userCode, String eMail) throws Exception;
    /**
     * 获取所有用户邮箱
     * @return
     */
    List<T482102Entity> getAccountList();
}
src/com/yc/crm/mail/service/MailAccountImpl.java
@@ -64,8 +64,8 @@
                    " invalid='" + account.isInvalid() + "',bisync_flag='" + account.isBiSyncFlag() + "',proxyFlag='" + account.isProxyFlag() + "'," +
                    " mailType=" + account.getMailType() + ",mailStatus=" + GridUtils.prossSqlParm(account.getMailStatus()) +
//                    " ,update_time=convert(varchar(19),getdate(),120) " +
                    " where userCode=" + GridUtils.prossSqlParm(account.getUserCode()) + " and accountId=" + account.getAccountId();
            sql += "select @@ROWCOUNT";
                    " where userCode=" + GridUtils.prossSqlParm(account.getUserCode()) + " and accountId=" + account.getAccountId() + "\n";
            sql += " select @@ROWCOUNT";
            return jdbcTemplate.queryForObject(sql, Integer.class);
        } catch (Exception e) {
            throw e;
@@ -78,8 +78,8 @@
        String sql = "set nocount on\n";
        try {
            sql += "update t482102 set update_time=convert(varchar(19),getdate(),120) " +
                    " where accountId=" + accountId;
            sql += "select @@ROWCOUNT";
                    " where accountId=" + accountId + "\n";
            sql += " select @@ROWCOUNT";
            return jdbcTemplate.queryForObject(sql, Integer.class);
        } catch (Exception e) {
            throw e;
@@ -92,8 +92,8 @@
        String sql = "set nocount on\n";
        try {
            sql += "update t482102 set mailStatus=" + GridUtils.prossSqlParm(status) + //",update_time=convert(varchar(19),getdate(),120) " +
                    " where accountId=" + accountId;
            sql += "select @@ROWCOUNT";
                    " where accountId=" + accountId + "\n";
            sql += " select @@ROWCOUNT";
            return jdbcTemplate.queryForObject(sql, Integer.class);
        } catch (Exception e) {
            throw e;
@@ -106,8 +106,8 @@
        String sql = "set nocount on\n";
        try {
            sql += "update t482102 set alias_email=" + GridUtils.prossSqlParm(aliasEmail) + //",update_time=convert(varchar(19),getdate(),120) " +
                    " where accountId=" + accountId;
            sql += "select @@ROWCOUNT";
                    " where accountId=" + accountId + "\n";
            sql += " select @@ROWCOUNT";
            return jdbcTemplate.queryForObject(sql, Integer.class);
        } catch (Exception e) {
            throw e;
@@ -128,6 +128,18 @@
    }
    @Override
    public List<T482102Entity> getAccountList() {
        String sql = "set nocount on\n";
        sql += "select companyId,companyName,email,password,alias_email as aliasEmail,userCode,userName,accountId,receive_server_user_name as receiveServerUserName," +
                "isnull(bisync_flag,0) as biSyncFlag,isnull(proxyFlag,0) as proxyFlag,mailDomain,isnull(mailType,0) as mailType,mailStatus,keywordList,siteUrl,receiveProtocol," +
                "receiveEmail,receivePassword,receiveSSL,receivePort,receiveHost,smtpEmail,smtpPassword,smtpSSL,smtpPort,smtpHost," +
                "isnull(invalid,0) as invalid,create_time as createTime,update_time as updateTime,DocVersion " +
                "from t482102 where invalid=1";
        sql += " order by accountId";
        return jdbcTemplate.query(sql, new BeanPropertyRowMapper<>(T482102Entity.class));
    }
    @Override
    public List<T482102Entity> getAccount(String userCode) {
        String sql = "set nocount on\n";
        try {
src/com/yc/crm/mail/service/MailFolderIfc.java
@@ -31,5 +31,5 @@
     * @param TextName
     * @return
     */
    List<T482107Entity> getMailFolder(String userCode,String search);
    List<T482107Entity> getMailFolder(String userCode);
}
src/com/yc/crm/mail/service/MailFolderImpl.java
@@ -3,7 +3,6 @@
import com.yc.action.grid.GridUtils;
import com.yc.crm.mail.entity.T482107Entity;
import com.yc.service.BaseService;
import org.apache.commons.lang3.StringUtils;
import org.springframework.jdbc.core.BeanPropertyRowMapper;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
@@ -68,15 +67,15 @@
    }
    @Override
    public List<T482107Entity> getMailFolder(String userCode, String search) {
    public List<T482107Entity> getMailFolder(String userCode) {
        String sql = "set nocount on\n";
        try {
            sql += "select companyId,companyName,folder_id,folder_name,userCode,userName,sort_id,create_time,update_time," +
                    "isnull(rowId,'') as rowId,treeControl," +
                    "isnull(parentRowId,'') as parentRowId from t482107 where userCode=" + GridUtils.prossSqlParm(userCode);
            if (StringUtils.isNotBlank(search)) {
                sql += " and folder_name like '%" + search + "%'";
            }
//            if (StringUtils.isNotBlank(search)) {
//                sql += " and folder_name like '%" + search + "%'";
//            }
            sql += " order by folder_id \n";
            return jdbcTemplate.query(sql, new BeanPropertyRowMapper<>(T482107Entity.class));
        } catch (Exception e) {
src/com/yc/crm/mail/service/MailIfc.java
@@ -28,7 +28,7 @@
     *
     * @param mail
     */
    void saveReceivingMailList(List<t482101HEntity> mail);
    String saveReceivingMailList(List<t482101HEntity> mail);
    /**
     * 更新收件内容
src/com/yc/crm/mail/service/MailImpl.java
@@ -1,7 +1,9 @@
package com.yc.crm.mail.service;
import com.yc.action.grid.GridUtils;
import com.yc.crm.base.entity.T482115Entity;
import com.yc.crm.mail.action.MailFolder;
import com.yc.crm.mail.action.MailTag;
import com.yc.crm.mail.entity.*;
import com.yc.entity.AttachmentConfig;
import com.yc.sdk.shopping.service.imagedata.ShoppingImageDataIfc;
@@ -75,14 +77,15 @@
    @Transactional(rollbackFor = Exception.class)
    @Override
    public void saveReceivingMailList(List<t482101HEntity> mail) {
    public String saveReceivingMailList(List<t482101HEntity> mail) {
        String sql = "set nocount on\n";
        try {
            sql += "declare @docCode varchar(50) ,@unid varchar(50),@fieldId varchar(100),@originalFileName varchar(100)," +
            sql += "declare @docCode varchar(50) ,@unid varchar(50),@fieldId varchar(100),@originalFileName varchar(100),@docCodeList varchar(3000)=''," +
                    "@physicalFile varchar(50),@OriginalPicture varbinary(max) \n";
            for (t482101HEntity m : mail) {//遍历内容
                sql += "exec sp_newdoccode 482101," + GridUtils.prossSqlParm(m.getUserCode()) + ",@docCode output \n";
                sql += "insert into t482101H(companyId,companyName,formId,docCode,docdate,PeriodID,postCode,postname,mailType,senderName,sender,sender_time,receiver,receiving_time," +
                sql += " select @docCodeList=@docCodeList+@docCode+';'\n" +//返回单号
                        "insert into t482101H(companyId,companyName,formId,docCode,docdate,PeriodID,postCode,postname,mailType,senderName,sender,sender_time,receiver,receiving_time," +
                        "cc,bcc,subject,userCode,userName,content,plain_text,messageId,read_flag,delete_flag,create_time,update_time," +
                        "attach_flag,attachment_list) values ";
                sql += "(" + GridUtils.prossSqlParm(m.getCompanyId()) + "," + GridUtils.prossSqlParm(m.getCompanyName()) + ",482101," +
@@ -96,7 +99,7 @@
                        m.getReadFlag() + "," + m.getDeleteFlag() + ",getdate(),getdate()," + m.getAttachFlag() + "," + GridUtils.prossSqlParm(m.getAttachmentList()) + ") \n" +
                        mailFileSql(m.getMailFile());
            }
            jdbcTemplate.update(sql);
            return jdbcTemplate.queryForObject(sql + "\n select @docCodeList", String.class);
        } catch (Exception e) {
            throw e;
        }
@@ -171,7 +174,7 @@
        String sql = "set nocount on\n";
        try {
            sql += "declare @docCode varchar(200) ='" + docCode + "' \n";
            sql += "delete t482101H where userCode =" + GridUtils.prossSqlParm(userCode) +
            sql += "update t482101H deleteFlag=1 where userCode =" + GridUtils.prossSqlParm(userCode) +
                    " and docCode in (select list from GetInStr(@docCode))\n";//标记删除
            sql += " select @@ROWCOUNT";
            return jdbcTemplate.queryForObject(sql, Integer.class);
@@ -185,7 +188,7 @@
        String sql = "set nocount on\n";
        try {
            sql += "declare @messageId varchar(200) ='" + messageId + "' \n";
            sql += "update  t482101H where messageId in (select list from GetInStr(@messageId))\n";//删除
            sql += " delete t482101H where messageId in (select list from GetInStr(@messageId))\n";//删除
            sql += " select @@ROWCOUNT";
            return jdbcTemplate.queryForObject(sql, Integer.class);
        } catch (Exception e) {
@@ -403,17 +406,28 @@
            for (MailModuleBelowEntity b : below) {
                String key = b.getKey();
                if (key.equals("moduleBelowA")) {//文件夹
                    List<T482107Entity> t482107 = mailFolderIfc.getMailFolder(userCode, "");
                    b.setList(MailFolder.getFolderList(t482107, ""));
                    List<T482107Entity> t482107 = mailFolderIfc.getMailFolder(userCode);
                    b.setList(MailFolder.getFolderModule(t482107, ""));
                }
                if (key.equals("moduleBelowB")) {//标签邮件
                    b.setList(mailTagIfc.getTagList(userCode, "", -1));
                    List<T482115Entity> tag = mailTagIfc.getTagList(userCode, "", -1);
                    b.setList(MailTag.getTagModule(tag));
                }
                if (key.equals("moduleBelowC")) {//显示更多
                    List<MailModuleBelowEntity> CList = new ArrayList<>();
                    MailModuleBelowEntity belowC = new MailModuleBelowEntity();
                    MailModuleBelowEntity delete = new MailModuleBelowEntity();
                    delete.setKey("deleteMail");
                    delete.setName("已删除邮件");
                    CList.add(delete);
                    MailModuleBelowEntity waste = new MailModuleBelowEntity();
                    waste.setKey("wasteMail");
                    waste.setName("垃圾邮件");
                    CList.add(waste);
                    MailModuleBelowEntity track = new MailModuleBelowEntity();
                    track.setKey("trackMail");
                    track.setName("追踪信息");
                    CList.add(track);
                    b.setList(CList);
                }
            }
            return below;
src/com/yc/crm/mail/service/MailServiceIfc.java
@@ -4,6 +4,7 @@
import com.yc.crm.mail.entity.T482102Entity;
import com.yc.crm.mail.entity.t482101HEntity;
import javax.mail.Message;
import javax.mail.MessagingException;
import javax.servlet.http.HttpServletRequest;
import java.io.IOException;
@@ -42,4 +43,12 @@
     */
    Integer setQuickReply(String docCode,String content) throws MessagingException;
    /**
     * 保存邮件内容
     * @param messages
     * @param email
     * @param foundation
     */
    public void setMailContent(Message[] messages, T482102Entity email, FoundationEntity foundation)throws
            Exception;
}
src/com/yc/crm/mail/service/MailServiceImpl.java
@@ -2,11 +2,14 @@
import com.sun.mail.imap.IMAPBodyPart;
import com.sun.mail.imap.IMAPStore;
import com.yc.action.grid.GridUtils;
import com.yc.crm.mail.action.MailPush;
import com.yc.crm.mail.entity.FoundationEntity;
import com.yc.crm.mail.entity.MailFileEntity;
import com.yc.crm.mail.entity.T482102Entity;
import com.yc.crm.mail.entity.t482101HEntity;
import com.yc.entity.attachment.AttachmentEntity;
import com.yc.factory.FactoryBean;
import com.yc.service.BaseService;
import org.apache.commons.io.FileUtils;
import org.apache.commons.lang3.StringUtils;
@@ -139,7 +142,11 @@
            properties.setProperty("mail.smtp.ssl.enable", emailEntity.isSmtpSSL() + "");// // 设置启用SSL加密
            properties.setProperty("mail.smtp.host", emailEntity.getSmtpHost());
            properties.setProperty("mail.smtp.port", emailEntity.getSmtpPort() + "");
            //Could not connect to SMTP host: smtp.qq.com, port: 465, response: -1 by danaus 2024-09-23 11:01
            // properties.setProperty("mail.smtp.socketFactory.class", "javax.net.ssl.SSLSocketFactory");
            // MailSSLSocketFactory sf = new MailSSLSocketFactory("TLSv1.2");
            // properties.put("mail.smtp.ssl.socketFactory", sf);
            // properties.setProperty("mail.smtp.ssl.protocols", "TLSv1.2");
//            properties.setProperty("mail.smtp.starttls.enable", "true");//// SMTP 协议设置 STARTTLS  开启tls
//            properties.setProperty("mail.smtp.socketFactory.port", emailEntity.getSmtpPort() + "");
@@ -271,6 +278,7 @@
     * @throws MessagingException
     * @throws IOException
     */
    @Override
    public void setMailContent(Message[] messages, T482102Entity email, FoundationEntity foundation) throws
            Exception {
        try {
@@ -342,7 +350,7 @@
                        List<MailFileEntity.MailBodyPart> part = new ArrayList<>();
                        String unId = UUID.randomUUID().toString().toUpperCase();
                        StringBuilder attachment = new StringBuilder();
                        result = getTextFromMimeMultipart((MimeMultipart) m.getContent(), plainText, part, unId, attachment);
                        result = getTextFromMimeMultipart((MimeMultipart) m.getContent(), plainText, part, unId, attachment, foundation.getDbId());
                        mailFile.setPart(part);
                        mailFile.setUnId(unId);//生成uuid
                        mail.setMailFile(mailFile);//附件添加到里面
@@ -390,8 +398,13 @@
                }
            }
            if (t482101HEntityList.size() > 0) {
                mailIfc.saveReceivingMailList(t482101HEntityList);//保存
                String docCodeList = mailIfc.saveReceivingMailList(t482101HEntityList);//保存
                mailAccountIfc.updateEmailTime(email.getAccountId());//更新一次配置
                //发送通知(极光和webscoket)
                //取用户的手机号
                BaseService baseService = (BaseService) FactoryBean.getBean("BaseService");
                String tel = baseService.getJdbcTemplate().queryForObject("select tel  from    _sys_LoginUser where usercode=" + GridUtils.prossSqlParm(foundation.getUserCode()), String.class);
                MailPush.pushEmailInfo(t482101HEntityList, docCodeList, foundation.getDbId(), tel);
            }
        } catch (Exception e) {
            throw e;
@@ -407,7 +420,7 @@
     */
    // 辅助方法,用于递归获取纯文本邮件内容
    private String getTextFromMimeMultipart(MimeMultipart mimeMultipart, StringBuilder
            plainText, List<MailFileEntity.MailBodyPart> part, String unId, StringBuilder attachment) throws Exception {
            plainText, List<MailFileEntity.MailBodyPart> part, String unId, StringBuilder attachment, Integer dbId) throws Exception {
        int count = mimeMultipart.getCount();
        if (count == 0) {
            throw new MessagingException("Multipart with no body parts");
@@ -453,7 +466,7 @@
                    String nextResult = result.toString();
                    if (nextResult.contains(cId)) {//有嵌套内容
                        //替换
                        nextResult = nextResult.replace("cid:" + cId + "", shoppingImageServer + "/uploads/email/82/482101/" + unId + "@p@" + p.getPhysicalFile());
                        nextResult = nextResult.replace("cid:" + cId + "", shoppingImageServer + "/uploads/email/" + dbId + "/482101/" + unId + "@p@" + p.getPhysicalFile());
                        result.setLength(0);//清空先
                        result.append(nextResult);
                    }
@@ -475,7 +488,7 @@
                    attachment.append(";" + fieldId);
                    part.add(p);
                } else if (bodyPart.isMimeType("multipart/*")) {
                    result.append(getTextFromMimeMultipart((MimeMultipart) bodyPart.getContent(), plainText, part, unId, attachment));
                    result.append(getTextFromMimeMultipart((MimeMultipart) bodyPart.getContent(), plainText, part, unId, attachment, dbId));
                }
            }
        }
src/com/yc/crm/mail/service/MailTagImpl.java
@@ -82,4 +82,6 @@
            throw e;
        }
    }
}
src/com/yc/crm/schedule/EmailSchedule.java
New file
@@ -0,0 +1,224 @@
package com.yc.crm.schedule;
import com.esotericsoftware.minlog.Log;
import com.sun.mail.imap.IMAPFolder;
import com.sun.mail.imap.IMAPStore;
import com.yc.api.schedule.ScheduleUtils;
import com.yc.crm.mail.entity.FoundationEntity;
import com.yc.crm.mail.entity.T482102Entity;
import com.yc.crm.mail.service.MailAccountIfc;
import com.yc.crm.mail.service.MailServiceIfc;
import com.yc.entity.AttachmentConfig;
import com.yc.entity.DataSourceEntity;
import com.yc.factory.FactoryBean;
import com.yc.multiData.MultiDataSource;
import com.yc.multiData.SpObserver;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationListener;
import org.springframework.context.event.ContextRefreshedEvent;
import org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor;
import org.springframework.scheduling.concurrent.ThreadPoolTaskScheduler;
import org.springframework.stereotype.Service;
import javax.mail.*;
import javax.mail.event.MessageCountEvent;
import javax.mail.event.MessageCountListener;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Properties;
/**
 * 实时监听邮箱
 */
@Slf4j
@Service
public class EmailSchedule implements ApplicationListener<ContextRefreshedEvent> {
    @Autowired
    ThreadPoolTaskExecutor threadPoolExecutor;
    @Autowired
    private ThreadPoolTaskScheduler threadPoolTaskScheduler;
    @Autowired
    MailAccountIfc emailAccountIfc;
    @Autowired
    MailServiceIfc mailServiceIfc;
    @Override
    public void onApplicationEvent(ContextRefreshedEvent contextRefreshedEvent) {
        if (contextRefreshedEvent.getApplicationContext().getParent() == null) {
            return;
        }
        threadPoolTaskScheduler = (ThreadPoolTaskScheduler) FactoryBean.getBean("threadPoolTaskScheduler");
        threadPoolExecutor = (ThreadPoolTaskExecutor) FactoryBean.getBean("threadPoolExecutor");
        String isStartUpSchedule = AttachmentConfig.get("isStartUpSchedule");//只在设置了定时任务的服务器上运行
        if ("1".equals(isStartUpSchedule)) {
            Map<String, DataSourceEntity> infoList = MultiDataSource.getDataSourceMaps();
            for (Map.Entry<String, DataSourceEntity> entry : infoList.entrySet()) {
                DataSourceEntity dataSourceEntity = entry.getValue();
                if (ScheduleUtils.isOnbusPlatform(dataSourceEntity) || dataSourceEntity.getDbId() == 1624) {
                    //dbid=1624,巴士软件(佛山公司),不需要执行定时任务
                    continue;
                }
          // if (dataSourceEntity.getDbId() != 82) continue;//TODO 测试用
               emailTask(dataSourceEntity);
            }
        }
    }
    private void emailTask(DataSourceEntity dataSourceEntity) {
            try {
                SpObserver.setDBtoInstance("_" + dataSourceEntity.getDbId());
                List<T482102Entity> list = emailAccountIfc.getAccountList();
                log.info(dataSourceEntity.getDbId()+"-加载邮箱数量:"+list.size());
                for (T482102Entity t482102Entity : list) {
                        threadPoolExecutor.execute(new checkEmailThread(t482102Entity,dataSourceEntity));
                }
            } catch (Exception e) {
                System.out.println("取不到邮箱设置内容:dbid=" + dataSourceEntity.getDbId() + ":" + e.getMessage());
                e.printStackTrace();
            } finally {
                SpObserver.setDBtoInstance();
            }
        }
    private class checkEmailThread implements Runnable {
        T482102Entity emailEntity;
        FoundationEntity foundation;
        DataSourceEntity dataSourceEntity;
        public checkEmailThread(T482102Entity t482102Entity, DataSourceEntity dataSourceEntity) {
            this.emailEntity = t482102Entity;
            this.dataSourceEntity = dataSourceEntity;
            foundation=new FoundationEntity();
            foundation.setDbId(dataSourceEntity.getDbId());
            foundation.setCompanyName(emailEntity.getCompanyName());
            foundation.setCompanyId(emailEntity.getCompanyId());
            foundation.setUserCode(emailEntity.getUserCode());
            foundation.setUserName(emailEntity.getUserName());
        }
        @Override
        public void run() {
            checkEmail();
    }
    private void checkEmail() {
        try {
            String protocol = emailEntity.getReceiveProtocol().toLowerCase();//接收协议 imap pop3
            String server = emailEntity.getReceiveHost();//"imap.qq.com";
            Integer port = emailEntity.getReceivePort();//993
            String user =emailEntity.getReceiveEmail();//邮箱
            String pwd = emailEntity.getReceivePassword();//密码
            Properties properties = new Properties();
            properties.setProperty("mail.store.protocol", protocol); // IMAP over SSL
            if (protocol.contains("imap")) {//接收协议imap
                properties.setProperty("mail.imaps.host", server);
                properties.setProperty("mail.imaps.port", port + "");
            } else if (protocol.contains("pop3")) {//接收协议pop3
                properties.setProperty("mail.pop3.host", server);
                properties.setProperty("mail.pop3.port", port + "");
            } else {//其他(再加)
                properties.setProperty("mail.imaps.host", server);
                properties.setProperty("mail.imaps.port", port + "");
            }
            HashMap IAM = new HashMap();
            //带上IMAP ID信息,由key和value组成,例如name,version,vendor,support-email等。
            IAM.put("name", user);
            IAM.put("version", emailEntity.getDocVersion() + "");
            IAM.put("vendor", emailEntity.getCompanyName());
            IAM.put("support-email", emailEntity.getEmail());
            //创建会话
            Session session = Session.getInstance(properties, new Authenticator() {
                @Override
                protected PasswordAuthentication getPasswordAuthentication() {
                    return new PasswordAuthentication(user, pwd);
                }
            });
            //存储对象
            IMAPStore store = (IMAPStore) session.getStore(protocol);//imap协议或pop3协议类型(推荐你使用IMAP协议来存取服务器上的邮件。)
            //连接
            store.connect(server, user, pwd);
            store.id(IAM);//163邮箱需要,不然会报:A3 NO SELECT Unsafe Login. Please contact kefu@188.com for help
            Folder folder = null;
            try {
                // 获得收件箱
                folder = store.getFolder("INBOX");
                // 以读写模式打开收件箱
                folder.open(Folder.READ_WRITE);
                log.info(emailEntity.getEmail() + "已就绪接收新邮件....");
                folder.addMessageCountListener(new MessageCountListener() {
                    @Override
                    public void messagesAdded(MessageCountEvent e) {
                        //TODO 处理新邮件
                        try {
                            SpObserver.setDBtoInstance("_" + dataSourceEntity.getDbId());
                            mailServiceIfc.setMailContent(e.getMessages(), emailEntity, foundation);
                        }catch (Exception e1){
                            e1.printStackTrace();
                        }finally {
                            SpObserver.setDBtoInstance();
                        }
                        log.info(emailEntity.getEmail()+":Message Count Event Fired");
                    }
                    @Override
                    public void messagesRemoved(MessageCountEvent e) {
                       // System.out.println(emailEntity.getEmail()+"Message Count Event Fired");
                    }
                });
               /* folder.addMessageChangedListener(new MessageChangedListener() {
                    @Override
                    public void messageChanged(MessageChangedEvent e) {
                        System.out.println(emailEntity.getEmail()+"Message Count Event Fired");
                    }
                });*/
                // Check mail once in "freq" MILLIseconds
                int freq = 2000;
                boolean supportsIdle = false;
                try {
                    if (folder instanceof IMAPFolder) {
                        IMAPFolder f = (IMAPFolder) folder;
                        f.idle();
                        supportsIdle = true;
                    }
                } catch (FolderClosedException fex) {
                    throw fex;
                } catch (MessagingException mex) {
                    supportsIdle = false;
                }
                for (; ; ) {
                    if (supportsIdle && folder instanceof IMAPFolder) {
                        IMAPFolder f = (IMAPFolder) folder;
                        f.idle();
                       // System.out.println(emailEntity.getEmail()+"IDLE done");
                    } else {
                        Thread.sleep(freq); // sleep for freq milliseconds
                        // This is to force the IMAP server to send us
                        // EXISTS notifications.
                        folder.getMessageCount();
                    }
                }
            } catch (FolderClosedException fe) {
                log.info("FolderClosedException......");
                checkEmail();
            } catch (Exception e) {
                throw new RuntimeException(e);
            } finally {
                try {
                    if (folder != null) {
                        folder.close(false);
                    }
                    if (store != null) {
                        store.close();
                    }
                } catch (MessagingException e) {
                    throw e;
                }
            }
        }catch (Exception e){
            e.printStackTrace();
        }
    }
}
}
src/com/yc/crm/schedule/MessagePopSchedule.java
@@ -49,17 +49,10 @@
                }
                //因为用户已下线,为了避免发送失败导致用户下次登录收不到通知的情况,取数及更新次数分开处理
                final List<MessageTipsEntity> list = doIfc.doQuery("set nocount on ; declare @UserCodes varchar(max) =" +GridUtils.prossSqlParm(joiner.toString())+
                        "\n select a.messid,a.messagetxt,a.unvaliddate,a.createuser,a.createtime,\n" +
                        " a.rejustsrvflag,a.Readers,a.UsrReaded,a.tipcount,a.formid,\n" +
                        " a.formtype,a.origfields,a.linkfields,a.linkmode,a.self_datafields,\n" +
                        " a.link_datafields,a.efilter , b.usercode ,a.url ,\n" +
                        " a.createusername ,a.topic ,a.messagetype ,a.isPublicUser,"+dataSourceEntity.getDbId()+"as dbid\n" +
                        "    from _sysMessageCount b  \n" +
                        "   join _sysmessage a on a.messid = b.messid\n" +
                        "\n select refid as id,userCode,userName,title,"+dataSourceEntity.getDbId()+"as dbid\n" +
                        "    from t482114 b  \n" +
                        "       where b.usercode in (select list from getinstr(@UserCodes))  \n" +
                        "       and b.tipcount < a.tipcount\n" +
                        "       and a.unvaliddate >= getdate() \n" +
                        "       and b.isRead = 0 ", MessageTipsEntity.class);
                        "       and b.isPost = 0 ", MessageTipsEntity.class);
            if (list != null && list.size() > 0) {
                final StringJoiner updateJoiner=new StringJoiner("\n");
                list.stream().unordered().distinct().forEach(x -> {
src/com/yc/open/baiwang/controller/BaiwangController.java
@@ -308,7 +308,7 @@
                String fielid = "InvoiceFile";//附件字段
                String unid = this.saveAttachment(outputFormatQueryQdInvoiceResponse, entity, fielid);
                //--更新状态
                baiwangIfc.updateByAttachment(entity, unid, fielid);
                baiwangIfc.updateByAttachment(entity, unid, fielid, outputFormatQueryQdInvoiceResponse, einvoiceInfo.getInvoiceNo());
            }
            callBackMessage.setData("成功");
            callBackMessage.setMemo("刷新成功").sendSuccessMessageByDefault();
src/com/yc/open/baiwang/schedule/QueryThread.java
@@ -9,6 +9,7 @@
import com.yc.open.baiwang.controller.BaiwangController;
import com.yc.open.baiwang.service.BaiwangIfc;
import com.yc.open.mutual.schedule.GateEntity;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
@@ -46,7 +47,9 @@
        messageInfo.setUserFromType(session.getAttribute(SessionKey.USER_LOGIN_TYPE) + "");
        messageInfo.setUserCode(session.getAttribute(SessionKey.USERCODE) + "");
        messageInfo.setSessionId(session.getId());*/
        int times=5;//重试5次
        try {
            while (times-- > 0) {
            Thread.sleep(5000);//暂停5秒
            //2---通过查询接口下载电子发票
            SpObserver.setDBtoInstance("_" + entity.getDbid());//切换数据源
@@ -58,6 +61,10 @@
            OutputFormatQueryQdInvoiceResponse outputFormatQueryQdInvoiceResponse = client.outputFormat().queryQdInvoice(query,
                    token);
            log.info("msg:" + JSON.toJSONString(outputFormatQueryQdInvoiceResponse));
            if(StringUtils.isBlank(outputFormatQueryQdInvoiceResponse.getResponse().getPdfUrl())){
                //查询不到pdf,需要重试
                continue;
            }
            if (!outputFormatQueryQdInvoiceResponse.isSuccess()) {
                //失败
                log.info(outputFormatQueryQdInvoiceResponse.getErrorResponse().getSubMessage());
@@ -65,7 +72,9 @@
            String fielid = "InvoiceFile";//附件字段
            String unid = baiwangController.saveAttachment(outputFormatQueryQdInvoiceResponse, entity, fielid);
            //--更新状态
            baiwangIfc.updateByAttachment(entity, unid, fielid);
            baiwangIfc.updateByAttachment(entity, unid, fielid,outputFormatQueryQdInvoiceResponse,invoiceNo);
            times=0;
            }
        }catch (Exception ex) {
            ex.printStackTrace();
        }finally {
src/com/yc/open/baiwang/service/BaiwangIfc.java
@@ -2,6 +2,7 @@
import com.baiwang.open.entity.request.OutputInvoiceIssueRequest;
import com.baiwang.open.entity.request.OutputRedinvoiceAddRequest;
import com.baiwang.open.entity.response.OutputFormatQueryQdInvoiceResponse;
import com.baiwang.open.entity.response.OutputInvoiceIssueResponse;
import com.baiwang.open.entity.response.OutputRedinvoiceAddResponse;
import com.yc.open.mutual.schedule.GateEntity;
@@ -15,7 +16,7 @@
    void updateRedStatus(GateEntity entity, OutputRedinvoiceAddResponse response);
    void updateByAttachment(GateEntity entity, String uuid, String fieldid);
    void updateByAttachment(GateEntity entity, String uuid, String fieldid, OutputFormatQueryQdInvoiceResponse outputFormatQueryQdInvoiceResponse, String invoiceNo);
    void sendLog(GateEntity entity, OutputInvoiceIssueResponse issue);
src/com/yc/open/baiwang/service/BaiwangImpl.java
@@ -6,6 +6,7 @@
import com.baiwang.open.entity.request.node.OutputInvoiceIssueInvoiceDetail;
import com.baiwang.open.entity.request.node.OutputInvoiceIssuePreInvoice;
import com.baiwang.open.entity.request.node.OutputRedinvoiceAddObjectType;
import com.baiwang.open.entity.response.OutputFormatQueryQdInvoiceResponse;
import com.baiwang.open.entity.response.OutputInvoiceIssueResponse;
import com.baiwang.open.entity.response.OutputRedinvoiceAddResponse;
import com.baiwang.open.entity.response.node.*;
@@ -383,9 +384,10 @@
    }
    @Transactional
    @Override
    public void updateByAttachment(GateEntity entity,String uuid, String fieldid) {
    public void updateByAttachment(GateEntity entity, String uuid, String fieldid, OutputFormatQueryQdInvoiceResponse outputFormatQueryQdInvoiceResponse, String invoiceNo) {
        String sql = " set nocount on \n " +
                " update a set a." + fieldid + "=" + GridUtils.prossSqlParm(uuid) + "  from t150504H a where a.doccode=" + GridUtils.prossSqlParm(entity.getDocCode()) + "\n" +
                " update t150523H set eInvoiceUrl="+GridUtils.prossSqlParm(outputFormatQueryQdInvoiceResponse.getResponse().getPdfUrl())+" where invoiceNo="+GridUtils.prossSqlParm(invoiceNo)+" \n" +
                " select @@rowcount";
        this.jdbcTemplate.queryForObject(sql, Integer.class);
    }