美文网首页工具类
Java.mail收发邮件和定位退回邮件

Java.mail收发邮件和定位退回邮件

作者: 星钻首席小管家 | 来源:发表于2021-12-28 11:37 被阅读0次

    1.MailUtil

    public class MailUtil {
    
        @Value("${mail.mark}")
        private String id;
    
        public static String mark;
    
        @PostConstruct
        public void init(){
             mark = this.id;
        }
    
        /**
         * 发送邮件
         * @param fromMailSMTPHost 邮件服务器
         * @param smtpPort 端口
         * @param fromMailAddress 发件地址
         * @param fromMailPwd 发件授权码
         * @param toEmailAddress 收件地址
         * @param emailContent 内容
         * @param emailTitle 标题
         * @param msgId 指定标识ID
         * @return
         */
        public static boolean sendEmail(String fromMailSMTPHost,String smtpPort,String fromMailAddress,
                                        String fromMailPwd, String toEmailAddress, String emailContent, String emailTitle,
                                        String msgId) {
            Session session = setSession(fromMailSMTPHost,smtpPort);
            try {
                Message message = setMail(session,fromMailAddress,toEmailAddress, emailTitle, emailContent,msgId);
                Transport transport = session.getTransport();
                transport.connect(fromMailAddress, fromMailPwd);
                transport.sendMessage(message, message.getAllRecipients());
                transport.close();
            } catch (Exception e) {
                log.error("toEmailAddress = " + toEmailAddress + ", emailContent = " + emailContent + ", emailTitle = " + emailTitle + ", error = " + e.getMessage());
                return false;
            }
            return true;
        }
    
        private static Properties setProperties(String fromMailSMTPHost,String smtpPort) {
            Properties properties = new Properties();
            properties.setProperty("mail.transport.protocol", "smtp");
            properties.setProperty("mail.smtp.host", fromMailSMTPHost);
            properties.setProperty("mail.smtp.auth", "true");
            properties.setProperty("mail.smtp.port", smtpPort);
            properties.setProperty("mail.smtp.socketFactory.class", "javax.net.ssl.SSLSocketFactory");
            properties.setProperty("mail.smtp.socketFactory.fallback", "false");
            properties.setProperty("mail.smtp.socketFactory.port", smtpPort);
            properties.setProperty("mail.smtp.ssl.enable", "true");
            properties.setProperty("mail.debug", "true");
            return properties;
        }
    
        private static Message setMail(Session session,String fromMailAddress, String toEmailAdress, String emailTitle,
                                       String emailContent,String messageId) throws Exception {
            MimeMessage message = new MimeMessage(session);
            message.setFrom(new InternetAddress(fromMailAddress, fromMailAddress, "UTF-8"));
            message.setRecipient(Message.RecipientType.TO, new InternetAddress(toEmailAdress, toEmailAdress, "UTF-8"));
            message.setSubject(emailTitle);
            message.setContent(emailContent, "text/html;charset=utf-8");
            message.setSentDate(new Date());
            message.addHeader(mark,messageId);
            message.saveChanges();
            return message;
        }
    
        private static Session setSession(String fromMailSMTPHost,String smtpPort) {
            Properties properties = setProperties(fromMailSMTPHost,smtpPort);
            Session session = Session.getInstance(properties);
            session.setDebug(true);
            return session;
        }
    
        public static void main(String[] args) {
            String fromMailAddress = "XX@qq.com";
            String fromMailPwd = "XXXX";
            String fromMailSMTPHost = "smtp.qq.com";
            String smtpPort = "465";
    
            String toEmailAddress = "XXXX@sina.com";
            String emailContent = "testContent1227";
            String emailTitle = "testTitle1227";
            UUID uuid = UUID.randomUUID();
            MailUtil.sendEmail(fromMailSMTPHost, smtpPort, fromMailAddress, fromMailPwd, toEmailAddress,
                    emailContent,
                    emailTitle, DateUtils.getTime()+"-"+uuid);
        }
    }
    

    2.EmailBounceScanService

    public class EmailBounceScanService {
    
        private static final String multipart = "multipart/*";
    
        private final static String subjectKeyword = "来自qq.com的退信";
    
        private final static String subjectKeyword163 = "系统退信";
    
        private Integer timeOffset = 1;
    
        private Properties buildInboxProperties(String popHost) {
            Properties properties = new Properties();
            // properties.setProperty("mail.store.protocol", "pop3");
            // properties.setProperty("mail.pop3.host", popHost);
            // properties.setProperty("mail.pop3.auth", "true");
            // properties.setProperty("mail.pop3.default-encoding", "UTF-8");
    
            properties.setProperty("mail.store.protocol", "imap");
            properties.setProperty("mail.imap.host", popHost);
            properties.setProperty("mail.imap.auth", "true");
            properties.setProperty("mail.imap.port", "993");
            properties.setProperty("mail.imap.socketFactory.class", "javax.net.ssl.SSLSocketFactory");
            properties.setProperty("mail.imap.socketFactory.fallback", "false");
            properties.setProperty("mail.imap.socketFactory.port", "993");
            properties.setProperty("mail.imap.ssl.enable", "true");
            properties.setProperty("mail.imap.default-encoding", "UTF-8");
            properties.setProperty("mail.debug", "true");
    
            return properties;
        }
    
        /**
         * 查找退回邮件
         * @param popHost
         * @param username
         * @param password
         */
        public void searchEmail163(String popHost,String username,String password) {
            //这部分就是解决异常的关键所在,设置IAMP ID信息
            HashMap IAM = new HashMap();
            //带上IMAP ID信息,由key和value组成,例如name,version,vendor,support-email等。
            // 这个value的值随便写就行
            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(this.buildInboxProperties(popHost));
            IMAPStore store = null;
            Folder receiveFolder = null;
            try {
                // 使用imap会话机制,连接服务器
                int total = 0;
                store =  (IMAPStore) session.getStore("imap");
                store.connect(username, password);
                store.id(IAM);
                receiveFolder = store.getFolder("inbox");
                receiveFolder.open(Folder.READ_ONLY);
    
                int messageCount = receiveFolder.getMessageCount();
                List<Message> list = new ArrayList<>();
                if (messageCount > 0) {
                    Date now = Calendar.getInstance().getTime();
                    Date timeOffsetAgo = DateUtils.getStartDate(DateUtils.getLastDay(timeOffset));
                    SearchTerm comparisonTermGe = new ReceivedDateTerm(ComparisonTerm.GE, timeOffsetAgo);
                    SearchTerm comparisonTermLe = new ReceivedDateTerm(ComparisonTerm.LE, now);
                    SearchTerm searchDate = new AndTerm(comparisonTermLe,comparisonTermGe);
                    SearchTerm searchFrom = new FromStringTerm("PostMaster");
                    SearchTerm search = new AndTerm(searchDate,searchFrom);
    
                    // Message[] messages = receiveFolder.search(search);
                    Message[] messages = receiveFolder.getMessages();
                    if (messages.length == 0) {
                        log.info("No bounce email was found.");
                        return;
                    }
                    for (Message message : messages) {
                        String subject = message.getSubject();
                        if(subjectKeyword163.equalsIgnoreCase(subject)){
                            list.add(message);
                        }
                    }
                    this.messageHandler(list);
                }
            } catch (MessagingException e) {
                log.error("Exception in searchInboxEmail {}", e.getMessage());
                e.printStackTrace();
            } finally {
                try {
                    if (receiveFolder != null) {
                        receiveFolder.close(true);
                    }
                    if (store != null) {
                        store.close();
                    }
                } catch (MessagingException e) {
                    log.error("Exception in searchInboxEmail {}", e.getMessage());
                    e.printStackTrace();
                }
            }
        }
    
        /**
         * 获取指定标识
         * @param part
         * @return
         * @throws Exception
         */
        public static HashMap<String, String> getMessageId163(Part part) throws Exception {
            HashMap<String, String> map = new HashMap<>();
            if (!part.isMimeType(multipart)) {
                return map;
            }
    
            Multipart multipart = (Multipart) part.getContent();
            for (int i = 0; i < multipart.getCount(); i++) {
                BodyPart bodyPart = multipart.getBodyPart(i);
    
                if (part.isMimeType("message/rfc822")) {
                    return getMessageId((Part) part.getContent());
                }
                InputStream inputStream = bodyPart.getInputStream();
    
                try (BufferedReader br = new BufferedReader(new InputStreamReader(inputStream))) {
                    String strLine;
                    String text = "";
                    while ((strLine = br.readLine()) != null) {
    
                        if (strLine.startsWith(MailUtil.mark)) {
                            String[] split = strLine.split(MailUtil.mark+":");
                            if(split.length > 1 && StringUtils.isNotEmpty(split[1].trim())){
                                map.put("id", split[1].trim());
                            }
                        }
                        String fromBase64 = Base64Utils.getFromBase64(strLine,"gb2312");
                        if(fromBase64.contains("退信原因:")) {
                            text = "\t"+fromBase64;
                        }
                    }
                    if(StringUtils.isNotEmpty(text)){
                        text = deleteAllHTMLTag(text);
                        text = text.replaceAll("\t", "");
                    }
                    if(StringUtils.isNotEmpty(text)){
                        map.put("text",text);
                    }
                }
            }
    
            return map;
        }
        /**
         * 查找退回邮件
         * @param popHost
         * @param username
         * @param password
         */
        public void searchInboxEmail(String popHost,String username,String password) {
            Session session = Session.getInstance(this.buildInboxProperties(popHost));
            Store store = null;
            Folder receiveFolder = null;
            try {
                store = session.getStore("imap");
                store.connect(username, password);
                receiveFolder = store.getFolder("inbox");
                receiveFolder.open(Folder.READ_ONLY);
    
                int messageCount = receiveFolder.getMessageCount();
                List<Message> list = new ArrayList<>();
                if (messageCount > 0) {
                    Date now = Calendar.getInstance().getTime();
                    Date timeOffsetAgo = DateUtils.getStartDate(DateUtils.getLastDay(timeOffset));
                    SearchTerm comparisonTermGe = new ReceivedDateTerm(ComparisonTerm.GE, timeOffsetAgo);
                    SearchTerm comparisonTermLe = new ReceivedDateTerm(ComparisonTerm.LE, now);
                    SearchTerm searchDate = new AndTerm(comparisonTermLe,comparisonTermGe);
                    SearchTerm searchFrom = new FromStringTerm("PostMaster");
                    SearchTerm search = new AndTerm(searchDate,searchFrom);
    
                    Message[] messages = receiveFolder.search(search);
                    if (messages.length == 0) {
                        log.info("No bounce email was found.");
                        return;
                    }
                    for (Message message : messages) {
                        String subject = message.getSubject();
                        if(subjectKeyword.equalsIgnoreCase(subject)){
                            list.add(message);
                        }
                    }
                    this.messageHandler(list);
                }
            } catch (MessagingException e) {
                log.error("Exception in searchInboxEmail {}", e.getMessage());
                e.printStackTrace();
            } finally {
                try {
                    if (receiveFolder != null) {
                        receiveFolder.close(true);
                    }
                    if (store != null) {
                        store.close();
                    }
                } catch (MessagingException e) {
                    log.error("Exception in searchInboxEmail {}", e.getMessage());
                    e.printStackTrace();
                }
            }
        }
    
        /**
         * 处理标识的邮件
         * @param messageList
         */
        @Transactional
        public void messageHandler(List<Message> messageList) {
            // messageList.stream().filter(MailUtil::isContainAttachment).forEach((message -> {
            messageList.stream().forEach((message -> {
                String messageId = null;
                String reason = null;
                try {
                    HashMap<String, String> mail = this.getMessageId(message);
                    messageId = mail.get("id");
                    reason = mail.get("text");
                } catch (Exception e) {
                    log.error("getMessageId:", e.getMessage());
                }
                if (StringUtils.isEmpty(messageId)) return;
    
                //todo 数据处理
            }));
        }
    
        /**
         * 处理中文编码问题
         * @param text
         * @return
         * @throws UnsupportedEncodingException
         */
        private String decodeText(String text) throws UnsupportedEncodingException {
            if (text == null) {
                return null;
            }
            if (text.startsWith("=?GB") || text.startsWith("=?gb"))
                text = MimeUtility.decodeText(text);
            else
                text = new String(text.getBytes("ISO8859_1"));
            return text;
        }
    
        /**
         * 获取指定标识
         * @param part
         * @return
         * @throws Exception
         */
        public static HashMap<String, String> getMessageId(Part part) throws Exception {
            HashMap<String, String> map = new HashMap<>();
            if (!part.isMimeType(multipart)) {
                return map;
            }
    
            Multipart multipart = (Multipart) part.getContent();
            for (int i = 0; i < multipart.getCount(); i++) {
                BodyPart bodyPart = multipart.getBodyPart(i);
    
                if (part.isMimeType("message/rfc822")) {
                    return getMessageId((Part) part.getContent());
                }
                InputStream inputStream = bodyPart.getInputStream();
    
                try (BufferedReader br = new BufferedReader(new InputStreamReader(inputStream))) {
                    String strLine;
                    boolean flag = false;
                    String text = "";
                    while ((strLine = br.readLine()) != null) {
                        if (strLine.startsWith(MailUtil.mark)) {
                            String[] split = strLine.split(MailUtil.mark+":");
                            if(split.length > 1 && StringUtils.isNotEmpty(split[1].trim())){
                                map.put("id", split[1].trim());
                            }
                        }
                        if(flag){
                            text = "\t"+strLine;
                        }
                        if(strLine.contains("退信原因")) {
                            flag = true;
                        }
                        if(text.contains("</td>")){
                            flag = false;
                        }
                    }
                    if(StringUtils.isNotEmpty(text)){
                        text = deleteAllHTMLTag(text);
                        text = text.replaceAll("\t", "");
                    }
                    if(StringUtils.isNotEmpty(text)){
                        map.put("text",text);
                    }
                }
            }
    
            return map;
        }
    
        /**
         * 删除所有的HTML标签
         *
         * @param source 需要进行除HTML的文本
         * @return
         */
        public static String deleteAllHTMLTag(String source) {
            if(source == null) {
                return "";
            }
            String s = source;
            /** 删除普通标签  */
            s = s.replaceAll("<(S*?)[^>]*>.*?|<.*? />", "");
            /** 删除转义字符 */
            s = s.replaceAll("&.{2,6}?;", "");
            return s;
        }
    
        /**
         * 是否存在附件
         * @param part
         * @return
         */
        public static boolean isContainAttachment(Part part) {
            boolean attachFlag = false;
            try {
                if (part.isMimeType(multipart)) {
                    Multipart mp = (Multipart) part.getContent();
                    for (int i = 0; i < mp.getCount(); i++) {
                        BodyPart mpart = mp.getBodyPart(i);
                        String disposition = mpart.getDisposition();
                        if ((disposition != null) && ((disposition.equals(Part.ATTACHMENT)) || (disposition.equals(Part.INLINE))))
                            attachFlag = true;
                        else if (mpart.isMimeType(multipart)) {
                            attachFlag = isContainAttachment((Part) mpart);
                        } else {
                            String contype = mpart.getContentType();
                            if (contype.toLowerCase().contains("application"))
                                attachFlag = true;
                            if (contype.toLowerCase().contains("name"))
                                attachFlag = true;
                        }
                    }
                } else if (part.isMimeType("message/rfc822")) {
                    attachFlag = isContainAttachment((Part) part.getContent());
                }
            } catch (MessagingException | IOException e) {
                e.printStackTrace();
            }
            return attachFlag;
        }
    
    }
    

    相关文章

      网友评论

        本文标题:Java.mail收发邮件和定位退回邮件

        本文链接:https://www.haomeiwen.com/subject/ozkpqrtx.html