JavaEmailUtil.java 13.4 KB
Newer Older
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18
package pwc.taxtech.atms.common.util;

/**
 * @version 1.0
 * @program: atms
 * @description:
 * @author: Kevin
 * @create: 2019-04-26 12:31
 **/

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;
import pwc.taxtech.atms.common.EncryptUtil;
import pwc.taxtech.atms.vat.entity.FileUpload;

import javax.mail.*;
19 20 21
import java.io.FileOutputStream;
import java.io.InputStream;
import java.util.*;
22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79

@Component
public class JavaEmailUtil {
    private Logger logger = LoggerFactory.getLogger(JavaEmailUtil.class);
    /**
     * 获取邮件内容
     *
     * @param args
     * @throws Exception
     */
    @Value("${email.host}")
    private String host;

    @Value("${email.store.protocol}")
    private String protocol;

    @Value("${email.address}")
    private String email;

    @Value("${email.password}")
    private String email_password;

    @Value("${email.aesKey}")
    private String aesKey;

    public static void main(String[] args) {
       /* EncryptUtil instance = EncryptUtil.getInstance();
        String aesKey = null;
        String password = null;
        try {
            aesKey = instance.getAESKey();
            System.out.println(aesKey);
            password = instance.AESencode("szg8571451", aesKey);
            System.out.println(password);
        } catch (Exception e) {
            e.printStackTrace();
        }
        String _password = instance.AESdecode(password, aesKey);
        System.out.println(_password);*/
        System.out.println(getZeroTime() + " ------" +  System.currentTimeMillis());

    }

    /**
     * @param init 是否数据初始化
     */
    public List<Map<String, Object>> getEmails(boolean init) throws Exception {
        logger.info("taxemail ``````````````````````````````````````````````````````````````````````````````````````````````````");

        EncryptUtil instance = EncryptUtil.getInstance();
        List<Map<String, Object>> emailList = new ArrayList<>();
        Properties props = new Properties();
        //设置邮件接收协议为pop3
        props.setProperty("mail.store.protocol", protocol);
        props.setProperty("mail.pop3.host", host);
        Session session = Session.getInstance(props);
        Store store = session.getStore(protocol);
        //连接要获取数据的邮箱 主机+用户名+密码
80
        logger.info("pass ``````````````````````````````````````````````````````````````````````````````````````````````````"+ EncryptUtil.AESdecode(email_password, aesKey));
81

82
        store.connect(host, email, EncryptUtil.AESdecode(email_password, aesKey));
83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199

        logger.info("connect ``````````````````````````````````````````````````````````````````````````````````````````````````"+store);
        Folder folder = store.getFolder("inbox");
        //设置邮件可读可写
        folder.open(Folder.READ_WRITE);

        logger.info("init  ``````````````````````````````````````````````````````````````````````````````````````````````````"+init);
        if (!init) {

            Message[] messages = folder.getMessages();
            logger.info("进入 ``````````````````````````````````````````````````````````````````````````````````````````````````"+messages);
            for (int i = 0; i < messages.length; i++) {
                Map<String, Object> map = new HashMap<>();
                //如果不是初始化,只读取从零点到当前时间的邮件
                if (getZeroTime() < messages[i].getSentDate().getTime() &&
                        messages[i].getSentDate().getTime() < System.currentTimeMillis()) {
                    //解析发件人地址
                    String address = messages[i].getFrom()[0].toString();
                    //logger.warn(address);
                    map.put("address", address);
                    //解析邮件主题
                    String subject = messages[i].getSubject();
                    //logger.warn(subject);
                    map.put("subject", subject);
                    //如果只是纯文本文件情况
                    //String content = (String) messages[i].getContent();
                    //MIME中包含文本情况
                    //getTextMultipart(messages[i]);
                    //MIME中包含图片情况
                    //getPicMultipart(messages[i]);
                    //MIME中包含附件情况
                    //getAttachmentMultipart(messages[i]);
                    //解析综合数据情况
                    map.put("sendDate", messages[i].getSentDate());
                    FileUpload allMultipart = getAllMultipart(messages[i], map);
                    if (allMultipart != null)
                        map.put("attachInfo", allMultipart);
                    int i1 = messages[i].getFrom()[0].toString().indexOf(" <");
                    int i2 = messages[i].getFrom()[0].toString().indexOf(">");
                    try {
                        map.put("from_person", messages[i].getFrom()[0].toString().substring(i1 + 1, i2));
                    } catch (Exception e) {
                        map.put("from_person", "未知发件人");
                        // e.printStackTrace();
                    }
                    //https://mp.weixin.qq.com/s/_tWq8QUl_db-GcUThIoY0Q
                    //https://mp.weixin.qq.com/s/hxZZMhDRHHu4LqkXczMztw'
                    int qqIndex = map.get("content").toString().indexOf("https://mp.weixin.qq.com");
                    if (qqIndex != -1) {
                        map.put("url", map.get("content").toString().substring(qqIndex, qqIndex + 59));
                        map.put("type", "0");
                    } else {
                        map.put("type", "1");
                    }
                }
            }
            folder.close(true);
            store.close();
        } else {
            Message[] messages = folder.getMessages();
            logger.info("进入 ``````````````````````````````````````````````````````````````````````````````````````````````````"+messages);
            for (int i = 0; i < messages.length; i++) {
                Map<String, Object> map = new HashMap<>();
                String address = messages[i].getFrom()[0].toString();
                logger.warn(address);
                map.put("address", address);
                String subject = messages[i].getSubject();
                logger.warn(subject);
                map.put("subject", subject);
                map.put("sendDate", messages[i].getSentDate());
                FileUpload allMultipart = getAllMultipart(messages[i], map);
                if (allMultipart != null)
                    map.put("attachInfo", allMultipart);
                int i1 = messages[i].getFrom()[0].toString().indexOf(" <");
                int i2 = messages[i].getFrom()[0].toString().indexOf(">");
                try {
                    map.put("from_person", messages[i].getFrom()[0].toString().substring(i1 + 1, i2 ));
                } catch (Exception e) {
                    map.put("from_person", "未知发件人");
                    // e.printStackTrace();
                }
                int qqIndex = map.get("content").toString().indexOf("https://mp.weixin.qq.com");
                if (qqIndex != -1) {
                    map.put("url", map.get("content").toString().substring(qqIndex, qqIndex + 49));
                    map.put("type", "0");
                } else {
                    map.put("type", "1");
                }
                emailList.add(map);
            }
            folder.close(true);
            store.close();
        }
        return emailList;
    }

    public static Long getZeroTime() {
        long current = System.currentTimeMillis();//当前时间毫秒数
        return current / (1000 * 3600 * 24) * (1000 * 3600 * 24) - TimeZone.getDefault().getRawOffset();//今天零点零分零秒的毫秒数
    }

    /**
     * 解析综合数据
     * @param part
     * @throws Exception
     */
    private FileUpload getAllMultipart(Part part, Map map) throws Exception {
        String contentType = part.getContentType();
        InputStream is;
        String fileName;
        int index = contentType.indexOf("name");
        boolean conName = false;
        if (index != -1) {
            conName = true;
        }
        //判断part类型
        if (part.isMimeType("text/plain") && !conName) {
200
            map.put("content", part.getContent());
201
        } else if (part.isMimeType("text/html") && !conName) {
202
            map.put("content", part.getContent());
203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326
        } else if (part.isMimeType("multipart/*")) {
            Multipart multipart = (Multipart) part.getContent();
            int counts = multipart.getCount();
            for (int i = 0; i < counts; i++) {
                //递归获取数据
                getAllMultipart(multipart.getBodyPart(i), map);
                //附件可能是截图或上传的(图片或其他数据)
                if (multipart.getBodyPart(i).getDisposition() != null) {
                    //附件为截图
                    if (multipart.getBodyPart(i).isMimeType("image/*")) {
                        is = multipart.getBodyPart(i)
                                .getInputStream();
                        String name = multipart.getBodyPart(i).getFileName();

                        //截图图片
                        if (name.startsWith("=?")) {
                            try {
                                fileName = name.substring(name.lastIndexOf(".") - 1, name.lastIndexOf("?="));
                            } catch (Exception ex) {
                                fileName = name;
                            }
                        } else {
                            //上传图片
                            fileName = name;
                        }
                    } else {
                        //其他附件
                        is = multipart.getBodyPart(i)
                                .getInputStream();
                        fileName = multipart.getBodyPart(i).getFileName();
                    }
                    // 将附件上传至文件服务器
                    /*ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
                    byte[] buff = new byte[100]; //buff用于存放循环读取的临时数据
                    int rc = 0;
                    while ((rc = is.read(buff, 0, 100)) > 0) {
                        byteArrayOutputStream.write(buff, 0, rc);
                    }
                    byte[] in_b = byteArrayOutputStream.toByteArray(); //in_b为转换之后的结果
                    if (in_b != null)*/
                    try {
                        //这里可以将我们的文件上传到文件服务器,在这里上传报错了,先注释掉
                        //FileUpload fileUpload = SpringContextUtil.didiFileUploadService.uploadFile(multipartFile, fileName, "邮箱附件");
                        return null;
                    } catch (Exception e) {
                        return null;
                    }
                }
            }
        } else if (part.isMimeType("message/rfc822")) {
            getAllMultipart((Part) part.getContent(), map);
        }
        return null;
    }

    /**
     * 解析附件内容
     *
     * @param part
     * @throws Exception
     */
    private static void getAttachmentMultipart(Part part) throws Exception {
        if (part.isMimeType("multipart/*")) {
            Multipart multipart = (Multipart) part.getContent();
            int count = multipart.getCount();
            for (int i = 0; i < count; i++) {
                BodyPart bodyPart = multipart.getBodyPart(i);
                if (bodyPart.getDisposition() != null) {
                    InputStream is = bodyPart.getInputStream();
                    FileOutputStream fos = new FileOutputStream("路径+文件名");
                    int len = 0;
                    byte[] bys = new byte[1024];
                    while ((len = is.read(bys)) != -1) {
                        fos.write(bys, 0, len);
                    }
                    fos.close();
                }
            }
        }

    }

    /**
     * 解析图片内容
     *
     * @param part
     * @throws Exception
     */
    private static void getPicMultipart(Part part) throws Exception {
        if (part.isMimeType("multipart/*")) {
            Multipart multipart = (Multipart) part.getContent();
            int count = multipart.getCount();
            for (int i = 0; i < count; i++) {
                BodyPart bodyPart = multipart.getBodyPart(i);
                if (bodyPart.isMimeType("image/*")) {
                    InputStream is = bodyPart.getInputStream();
                    FileOutputStream fos = new FileOutputStream("路径+文件名");
                    int len = 0;
                    byte[] bys = new byte[1024];
                    while ((len = is.read(bys)) != -1) {
                        fos.write(bys, 0, len);
                    }
                    fos.close();
                }
            }
        }
    }

    /**
     * 解析文本内容
     *
     * @param part
     * @throws Exception
     */
    private static void getTextMultipart(Part part) throws Exception {
        if (part.isMimeType("text/html")) {
            String content = (String) part.getContent();
            System.out.println(content);
        } else if (part.isMimeType("text/plain")) {
            String content = (String) part.getContent();
            System.out.println(content);
        }
    }
}