接收邮件

package com.centnet.chakra.madara.out.task;


import cn.hutool.extra.mail.MailUtil;
import com.centnet.chakra.api.base.BaseConstants;
import com.centnet.chakra.api.base.KafkaTopic;
import com.centnet.chakra.boundary.api.BoundaryService;
import com.centnet.chakra.core.properties.ChakraProperties;
import com.centnet.chakra.core.utils.DateUtil;
import com.centnet.chakra.foundation.api.FileSystemService;
import com.centnet.chakra.madara.common.properties.MadaraProperties;
import com.centnet.chakra.madara.common.ro.ArchivesUploadRo;
import com.centnet.chakra.service.exception.BusinessException;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import javax.mail.*;
import javax.mail.internet.MimeUtility;
import javax.mail.search.FlagTerm;
import java.io.*;
import java.util.HashMap;
import java.util.Properties;
import java.util.concurrent.Executor;


/**
 *
 * 腾讯反馈信息流数据(Excel)定时任务
 *
 */
@Slf4j
@Component
public class TXInfoFlowFeedExcelTask {

    @Autowired
    private Executor executor;

    @Autowired
    private FileSystemService fileSystemService;

    @Autowired
    private MadaraProperties madaraProperties ;

    @Autowired
    private BoundaryService boundaryService ;


    private final static String port = "993";
    //腾讯企业邮箱接收的imap
    private final static String IMAP_SERVER = "imap.exmail.qq.com";
    private final static String protocol = "imap";
    private final static String SSL_FACTORY = "javax.net.ssl.SSLSocketFactory";

    /**
     * 每5分钟查询一次未读消息
     */
    @Scheduled(cron = "0 0/2 * * * ? ")
    public void send() {
        executor.execute(() -> {
            try {
                receiveFeedBackEmail();
            } catch (Exception e) {
                log.error("腾讯嫌疑人信息反馈邮件处理失败,错误信息:{}", e.getMessage());
                e.printStackTrace();
            }
        });
    }

    private void receiveFeedBackEmail() throws MessagingException {
        Properties props = new Properties();
        props.setProperty("mail.imap.socketFactory.class", SSL_FACTORY);
        props.setProperty("mail.imap.socketFactory.fallback", "false");
        //使用协议
        props.setProperty("mail.transport.protocol", protocol);
        props.setProperty("mail.imap.port", port);
        props.setProperty("mail.imap.socketFactory.port", port);
        // 获取连接
        Session session = Session.getDefaultInstance(props);
        session.setDebug(false);
        Store store = null ;
        Folder folder = null ;
        // 登陆认证
        try{
            // 获取Store对象
            store = session.getStore(protocol);
            store.connect(IMAP_SERVER, madaraProperties.getDataCollision().getAcceptEmailAccount(), madaraProperties.getDataCollision().getAcceptEmailPwd());
            // 获得用户的邮件帐户 通过imap协议获得Store对象调用这个方法时,邮件夹名称只能指定为"INBOX"
            folder = store.getFolder("INBOX");
            // 设置对邮件帐户的访问权限
            folder.open(Folder.READ_WRITE);
            //没有未读文件直接返回
            if(folder.getUnreadMessageCount()<=0){
                return;
            }
            // 得到未读数量   false代表未读,true代表已读
            FlagTerm ft = new FlagTerm(new Flags(Flags.Flag.SEEN), false);
            Message[] messages = folder.search(ft);
            for (Message message : messages) {
                //邮件的解析
                parseMultipart((Multipart) message.getContent());
                //读取后邮件状态会变为已读,设为已读
                message.setFlag(Flags.Flag.SEEN, true);
            }
        } catch (IOException e) {
           log.error(" 读取腾讯反馈信息流数据(Excel)失败:{}",e.getMessage());
        } finally {
            if(folder != null){
                // 关闭邮件夹对象
                folder.close(true);
            }
            if(store != null){
                // 关闭连接对象
                store.close();
            }
        }

    }

    /**
     *  解析邮件并将附件发回到内网
     */
    private void parseMultipart(Multipart content) throws MessagingException, IOException {
        for (int i = 0; i < content.getCount(); i++) {
            BodyPart bodyPart = content.getBodyPart(i);
             if (bodyPart.isMimeType("application/octet-stream")) {
                String disposition = bodyPart.getDisposition();
                if (disposition.equalsIgnoreCase(BodyPart.ATTACHMENT)) {
                    InputStream is = bodyPart.getInputStream();
                    //MimeUtility.decodeText解决附件名乱码问题
                    String strFileName = MimeUtility.decodeText(bodyPart.getFileName());
                    String filepath = ChakraProperties.getTempPath() + strFileName;
                    saveFile(is, new FileOutputStream(filepath));
                    FileInputStream fileInputStream = new FileInputStream(filepath);
                    //上传附件
                    byte[] readAllBytes = fileInputStream.readAllBytes();
                    //发送到内网
                    boundaryService.sendFile(KafkaTopic.INFO_FLOW_TX_INNER,null,strFileName,readAllBytes);
                }
            } else if (bodyPart.isMimeType("multipart/*")) {
                Multipart mpart = (Multipart) bodyPart.getContent();
                //邮件的解析
                parseMultipart(mpart);
            }
        }
    }

    /**
     * 保存到项目临时路径下
     * @param is
     * @param os
     * @throws IOException
     */
    public static void saveFile(InputStream is, OutputStream os) throws IOException {
        byte[] bytes = new byte[1024];
        int len = 0;
        while ((len = is.read(bytes)) != -1) {
            os.write(bytes, 0, len);
        }
        if (os != null) {
            os.close();
        }
        if (is != null) {
            is.close();
        }
    }


}

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值