Search in sources :

Example 11 with FromStringTerm

use of javax.mail.search.FromStringTerm in project javautils by jiadongpo.

the class CBCMailFetch method fetchMail2.

/**
 * 处理email
 *
 * @throws Exception
 */
public void fetchMail2() throws Exception {
    System.out.println("===================fetchMail2===================");
    Properties props = new Properties();
    props.setProperty("mail.pop3.port", "995");
    props.setProperty("mail.pop3.disabletop", "true");
    props.setProperty("mail.pop3.ssl.enable", "true");
    props.setProperty("mail.pop3.useStartTLS", "true");
    props.setProperty("mail.pop3.host", "pop3.yeepay.com");
    props.setProperty("mail.pop3.socketFactory.port", "995");
    props.setProperty("mail.pop3.socketFactory.fallback", "false");
    props.setProperty("mail.pop3.socketFactory.class", "javax.net.ssl.SSLSocketFactory");
    Session session = Session.getInstance(props);
    Folder inbox = null;
    Store store = session.getStore("pop3");
    try {
        store.connect("pop3.yeepay.com", receiveEmailAddress, receiveEmailPassword);
        Folder folder = store.getDefaultFolder();
        if (folder == null) {
            throw new MessagingException("读取邮箱失败。");
        }
        inbox = folder.getFolder("INBOX");
        inbox.open(Folder.READ_ONLY);
        System.out.println("连接成功,开始读取邮箱信息.");
        FetchProfile profile = new FetchProfile();
        profile.add(FetchProfile.Item.ENVELOPE);
        // 搜索发件人为”智联招聘“或主题包含”中国建设银行“的邮件
        // SearchTerm subjectTerm = new SubjectTerm("中国建设银行");//收件箱主题过滤
        // SearchTerm addressTerm = new FromTerm(new InternetAddress("295445156@qq.com"));//发件人地址
        SearchTerm andTerm = new AndTerm(new FromStringTerm(fromMailAddress), new SubjectTerm("中国建设银行"));
        Message[] messages = inbox.search(andTerm);
        // Message[] messages = inbox.getMessages();
        inbox.fetch(messages, profile);
        System.out.println("收件箱的邮件数:" + messages.length);
        CBCMailFetch pmm = null;
        for (int i = 0; i < messages.length; i++) {
            // 邮件发送者、邮件标题、邮件大小、邮件发送时间
            String from = Const.decodeText(messages[i].getFrom()[0].toString());
            InternetAddress ia = new InternetAddress(from);
            System.out.println("邮件信息,发送者:[" + ia.getPersonal() + "],发件人邮箱地址:[" + (ia.getAddress()) + "],标题:[" + messages[i].getSubject() + "],邮件大小:[" + messages[i].getSize() + "],发送时间:[" + messages[i].getSentDate() + "]");
            pmm = new CBCMailFetch((MimeMessage) messages[i]);
            Message message = messages[i];
            Multipart multipart = (Multipart) message.getContent();
            for (int j = 0, n = multipart.getCount(); j < n; j++) {
                Part part = multipart.getBodyPart(j);
                String disposition = part.getDisposition();
                if (disposition != null && ((disposition.equals(Part.ATTACHMENT) || (disposition.equals(Part.INLINE))))) {
                    String attachmentName = part.getFileName();
                    System.out.println(attachmentName);
                    // SHOP.105584045110069.20161028.zip
                    String[] attachmentNames = attachmentName.split("\\.");
                    if (attachmentNames.length != 4) {
                        System.out.println(Arrays.toString(attachmentNames));
                        // 结构不对
                        continue;
                    }
                    System.out.println("第一个元素:" + attachmentNames[0] + "第二个元素:" + attachmentNames[1] + "第三个元素:" + attachmentNames[2] + "第四个元素:" + attachmentNames[3]);
                    // 格式化日期
                    DateFormat format = new SimpleDateFormat("yyyyMMdd");
                    Date date = null;
                    String str = null;
                    try {
                        // Thu Jan 18 00:00:00 CST 2007
                        date = format.parse(attachmentNames[2]);
                    } catch (ParseException e) {
                        System.out.println("日期格式化错误:" + e);
                        e.printStackTrace();
                    }
                    // 昨天到当前(昨天的0点,到当前时间点)的数据或指定的数据
                    boolean configFlag = getSpecifiedDate().contains(attachmentNames[2]);
                    boolean yesterday = date.after(Const.lastDayWholePointDate(new Date())) && date.before(new Date());
                    // TODO 临时去掉,为了方便测试
                    // if (configFlag || yesterday) {
                    // 105110054111509为建行豹子8011   //105584045110069建行斑马8010
                    File file = pmm.getOutFile(attachmentName);
                    if (file.exists()) {
                        // 已存在的文件跳过
                        continue;
                    }
                    if (attachmentNames[1].equals("105110054111509") || attachmentNames[1].equals("105584045110069")) {
                        pmm.saveFile(file, part.getInputStream());
                        // 解压
                        String fileFullName = file.getAbsolutePath();
                        String fileFullDirTmp = file.getParent() + "/tmp_" + attachmentName;
                        fileFullDirTmp = fileFullDirTmp.substring(0, fileFullDirTmp.length() - 4);
                        unzip(fileFullName, fileFullDirTmp);
                        // 获取解压后的文件全路径
                        List<File> files = Const.searchFile(new File(fileFullDirTmp), ".det.");
                        for (File onefile : files) {
                            // 发送到指定ftp,后删除生成的目录
                            SFTPPUT sftpput = new SFTPPUT();
                            String ftpRemote = "/apps/tomcat7-40-tomcat-air-ticket-merchant/logs" + "/" + onefile.getName();
                            System.out.println("文件路径[" + onefile.getAbsolutePath() + "],上传至ftp路径[" + ftpRemote + "]");
                            sftpput.put(onefile.getAbsolutePath(), ftpRemote);
                            // 删除生成的目录
                            Const.delFolder(onefile.getParent());
                        }
                    }
                // }
                }
            }
        }
    } finally {
        try {
            inbox.close(false);
        } catch (Exception e) {
        }
        try {
            store.close();
        } catch (Exception e) {
        }
    }
}
Also used : InternetAddress(javax.mail.internet.InternetAddress) MimeMessage(javax.mail.internet.MimeMessage) AndTerm(javax.mail.search.AndTerm) MimeMessage(javax.mail.internet.MimeMessage) SearchTerm(javax.mail.search.SearchTerm) SubjectTerm(javax.mail.search.SubjectTerm) URISyntaxException(java.net.URISyntaxException) ParseException(java.text.ParseException) FromStringTerm(javax.mail.search.FromStringTerm) SimpleDateFormat(java.text.SimpleDateFormat) DateFormat(java.text.DateFormat) ParseException(java.text.ParseException) SimpleDateFormat(java.text.SimpleDateFormat)

Example 12 with FromStringTerm

use of javax.mail.search.FromStringTerm in project opentest by mcdcorp.

the class ReadEmailImap method run.

@Override
public void run() {
    super.run();
    final String DATE_TIME_FORMAT = "yyyy-MM-dd HH:mm:ss";
    DateTimeFormatter dateTimeFormatter = DateTimeFormatter.ofPattern(DATE_TIME_FORMAT);
    String defaultSentAfterTime = LocalDateTime.now().minusDays(365).format(dateTimeFormatter);
    String imapServer = this.readStringArgument("server");
    Integer port = this.readIntArgument("port", null);
    String subjectContains = this.readStringArgument("subjectContains", this.readStringArgument("subject", null));
    Pattern subjectRegex = this.readRegexArgument("subjectRegex", null);
    String bodyContains = this.readStringArgument("bodyContains", null);
    Pattern bodyRegex = this.readRegexArgument("bodyRegex", null);
    String fromAddress = this.readStringArgument("from", null);
    String sentAfter = this.readStringArgument("sentAfter", defaultSentAfterTime);
    String userName = this.readStringArgument("userName");
    String password = this.readStringArgument("password");
    Integer maxResults = this.readIntArgument("maxResults", 1);
    Integer minResults = this.readIntArgument("minResults", 1);
    LocalDateTime sentAfterDate = LocalDateTime.parse(sentAfter, dateTimeFormatter);
    ZonedDateTime sentAfterZonedDate = ZonedDateTime.of(sentAfterDate, ZoneId.systemDefault());
    Folder inbox = null;
    Store store = null;
    try {
        Session session = Session.getDefaultInstance(System.getProperties());
        store = session.getStore("imaps");
        if (port == null) {
            store.connect(imapServer, userName, password);
        } else {
            store.connect(imapServer, port, userName, password);
        }
        inbox = store.getFolder("Inbox");
        inbox.open(Folder.READ_ONLY);
        SentDateTerm sentDateTerm = new SentDateTerm(ComparisonTerm.GE, Date.from(sentAfterZonedDate.toInstant()));
        SearchTerm searchTerm = sentDateTerm;
        if (subjectContains != null) {
            SubjectTerm subjectTerm = new SubjectTerm(subjectContains);
            searchTerm = new AndTerm(searchTerm, subjectTerm);
        }
        if (bodyContains != null) {
            BodyTerm bodyTerm = new BodyTerm(bodyContains);
            searchTerm = new AndTerm(searchTerm, bodyTerm);
        }
        if (fromAddress != null) {
            FromStringTerm fromTerm = new FromStringTerm(fromAddress);
            searchTerm = new AndTerm(searchTerm, fromTerm);
        }
        List<Message> allMessages = Arrays.asList(inbox.search(searchTerm));
        int resultsIndex = 0;
        ArrayList<HashMap<String, String>> resultMessages = new ArrayList<>();
        while (resultMessages.size() < maxResults) {
            resultsIndex++;
            if (resultsIndex > allMessages.size()) {
                break;
            }
            Message currentMessage = allMessages.get(allMessages.size() - resultsIndex);
            // Make sure the sent date and time is after the specified
            // one. Since javax.mail only takes the date into consideration
            // and ignores the time, we might end up with messages sent earlier
            // than the time specified, so we must check this ourselves
            boolean sentDateIsInRange = currentMessage.getSentDate().after(Date.from(sentAfterZonedDate.toInstant()));
            if (!sentDateIsInRange) {
                continue;
            }
            String subject = currentMessage.getSubject();
            if (subjectRegex != null && !subjectRegex.matcher(subject).find()) {
                continue;
            }
            String body = this.getTextFromMessage(currentMessage);
            if (bodyRegex != null && !bodyRegex.matcher(body).find()) {
                continue;
            }
            HashMap resultMessage = new HashMap<>();
            resultMessage.put("subject", subject);
            resultMessage.put("body", body);
            resultMessage.put("from", getEmailAddresses(currentMessage.getFrom()));
            resultMessage.put("to", getEmailAddresses(currentMessage.getAllRecipients()));
            LocalDateTime sentDate = LocalDateTime.ofInstant(currentMessage.getSentDate().toInstant(), ZoneId.systemDefault());
            resultMessage.put("sentDate", sentDate.format(dateTimeFormatter));
            HashMap<String, String> headers = new HashMap<>();
            Enumeration headersIterator = currentMessage.getAllHeaders();
            while (headersIterator.hasMoreElements()) {
                Header header = (Header) headersIterator.nextElement();
                headers.put(header.getName(), header.getValue());
            }
            resultMessage.put("headers", headers);
            resultMessages.add(resultMessage);
        }
        if (resultMessages.size() < minResults) {
            throw new RuntimeException(String.format("We were expecting to find at least %s email message(s) matching the " + "given criteria, but we found %s. You can set the minimum number " + "of messages expected by using the \"minResults\" argument.", minResults, resultMessages.size()));
        } else {
            Logger.info(String.format("We found %s email message(s) matching the given criteria", resultMessages.size()));
        }
        this.writeOutput("emails", ScriptUtils.wrapArray(resultMessages.toArray()));
        // Write the details of the most recent message again, to
        // dedicated output values. These three output values will be
        // deprecated and are only populated for backward compatibility.
        HashMap mostRecentMessage = resultMessages.get(0);
        this.writeOutput("subject", mostRecentMessage.get("subject"));
        this.writeOutput("body", mostRecentMessage.get("body"));
        this.writeOutput("from", mostRecentMessage.get("from"));
    } catch (Exception ex) {
        throw new RuntimeException(String.format("Failed to read emails from server %s", imapServer), ex);
    } finally {
        try {
            if (inbox != null) {
                inbox.close(true);
            }
            if (store != null) {
                store.close();
            }
        } catch (MessagingException ex) {
            Logger.error("Failed to close the email store and/or folder", ex);
        }
    }
}
Also used : LocalDateTime(java.time.LocalDateTime) Message(javax.mail.Message) HashMap(java.util.HashMap) ArrayList(java.util.ArrayList) Store(javax.mail.Store) SentDateTerm(javax.mail.search.SentDateTerm) Folder(javax.mail.Folder) AndTerm(javax.mail.search.AndTerm) ZonedDateTime(java.time.ZonedDateTime) BodyTerm(javax.mail.search.BodyTerm) Pattern(java.util.regex.Pattern) Enumeration(java.util.Enumeration) MessagingException(javax.mail.MessagingException) SearchTerm(javax.mail.search.SearchTerm) SubjectTerm(javax.mail.search.SubjectTerm) MessagingException(javax.mail.MessagingException) FromStringTerm(javax.mail.search.FromStringTerm) Header(javax.mail.Header) DateTimeFormatter(java.time.format.DateTimeFormatter) Session(javax.mail.Session)

Aggregations

FromStringTerm (javax.mail.search.FromStringTerm)12 SearchTerm (javax.mail.search.SearchTerm)12 AndTerm (javax.mail.search.AndTerm)7 SubjectTerm (javax.mail.search.SubjectTerm)6 Test (org.junit.Test)6 RecipientStringTerm (javax.mail.search.RecipientStringTerm)5 OrTerm (javax.mail.search.OrTerm)4 URISyntaxException (java.net.URISyntaxException)3 DateFormat (java.text.DateFormat)3 ParseException (java.text.ParseException)3 SimpleDateFormat (java.text.SimpleDateFormat)3 InternetAddress (javax.mail.internet.InternetAddress)3 MimeMessage (javax.mail.internet.MimeMessage)3 NotTerm (javax.mail.search.NotTerm)2 LocalDateTime (java.time.LocalDateTime)1 ZonedDateTime (java.time.ZonedDateTime)1 DateTimeFormatter (java.time.format.DateTimeFormatter)1 ArrayList (java.util.ArrayList)1 Enumeration (java.util.Enumeration)1 HashMap (java.util.HashMap)1