Example usage for javax.mail Message getReceivedDate

List of usage examples for javax.mail Message getReceivedDate

Introduction

In this page you can find the example usage for javax.mail Message getReceivedDate.

Prototype

public abstract Date getReceivedDate() throws MessagingException;

Source Link

Document

Get the date this message was received.

Usage

From source file:com.cws.esolutions.core.utils.EmailUtils.java

/**
 * Processes and sends an email message as generated by the requesting
 * application. This method is utilized with a JNDI datasource.
 *
 * @param dataSource - The email message
 * @param authRequired - <code>true</code> if authentication is required, <code>false</code> otherwise
 * @param authList - If authRequired is true, this must be populated with the auth info
 * @return List - The list of email messages in the mailstore
 * @throws MessagingException {@link javax.mail.MessagingException} if an exception occurs during processing
 *//*from  w w  w .ja  v a2s  . com*/
public static final synchronized List<EmailMessage> readEmailMessages(final Properties dataSource,
        final boolean authRequired, final List<String> authList) throws MessagingException {
    final String methodName = EmailUtils.CNAME
            + "#readEmailMessages(final Properties dataSource, final boolean authRequired, final List<String> authList) throws MessagingException";

    if (DEBUG) {
        DEBUGGER.debug(methodName);
        DEBUGGER.debug("dataSource: {}", dataSource);
        DEBUGGER.debug("authRequired: {}", authRequired);
        DEBUGGER.debug("authList: {}", authList);
    }

    Folder mailFolder = null;
    Session mailSession = null;
    Folder archiveFolder = null;
    List<EmailMessage> emailMessages = null;

    Calendar cal = Calendar.getInstance();
    cal.add(Calendar.HOUR, -24);

    final Long TIME_PERIOD = cal.getTimeInMillis();
    final URLName URL_NAME = (authRequired)
            ? new URLName(dataSource.getProperty("mailtype"), dataSource.getProperty("host"),
                    Integer.parseInt(dataSource.getProperty("port")), null, authList.get(0), authList.get(1))
            : new URLName(dataSource.getProperty("mailtype"), dataSource.getProperty("host"),
                    Integer.parseInt(dataSource.getProperty("port")), null, null, null);

    if (DEBUG) {
        DEBUGGER.debug("timePeriod: {}", TIME_PERIOD);
        DEBUGGER.debug("URL_NAME: {}", URL_NAME);
    }

    try {
        // Set up mail session
        mailSession = (authRequired) ? Session.getDefaultInstance(dataSource, new SMTPAuthenticator())
                : Session.getDefaultInstance(dataSource);

        if (DEBUG) {
            DEBUGGER.debug("mailSession: {}", mailSession);
        }

        if (mailSession == null) {
            throw new MessagingException("Unable to configure email services");
        }

        mailSession.setDebug(DEBUG);
        Store mailStore = mailSession.getStore(URL_NAME);
        mailStore.connect();

        if (DEBUG) {
            DEBUGGER.debug("mailStore: {}", mailStore);
        }

        if (!(mailStore.isConnected())) {
            throw new MessagingException("Failed to connect to mail service. Cannot continue.");
        }

        mailFolder = mailStore.getFolder("inbox");
        archiveFolder = mailStore.getFolder("archive");

        if (!(mailFolder.exists())) {
            throw new MessagingException("Requested folder does not exist. Cannot continue.");
        }

        mailFolder.open(Folder.READ_WRITE);

        if ((!(mailFolder.isOpen())) || (!(mailFolder.hasNewMessages()))) {
            throw new MessagingException("Failed to open requested folder. Cannot continue");
        }

        if (!(archiveFolder.exists())) {
            archiveFolder.create(Folder.HOLDS_MESSAGES);
        }

        Message[] mailMessages = mailFolder.getMessages();

        if (mailMessages.length == 0) {
            throw new MessagingException("No messages were found in the provided store.");
        }

        emailMessages = new ArrayList<EmailMessage>();

        for (Message message : mailMessages) {
            if (DEBUG) {
                DEBUGGER.debug("MailMessage: {}", message);
            }

            // validate the message here
            String messageId = message.getHeader("Message-ID")[0];
            Long messageDate = message.getReceivedDate().getTime();

            if (DEBUG) {
                DEBUGGER.debug("messageId: {}", messageId);
                DEBUGGER.debug("messageDate: {}", messageDate);
            }

            // only get emails for the last 24 hours
            // this should prevent us from pulling too
            // many emails
            if (messageDate >= TIME_PERIOD) {
                // process it
                Multipart attachment = (Multipart) message.getContent();
                Map<String, InputStream> attachmentList = new HashMap<String, InputStream>();

                for (int x = 0; x < attachment.getCount(); x++) {
                    BodyPart bodyPart = attachment.getBodyPart(x);

                    if (!(Part.ATTACHMENT.equalsIgnoreCase(bodyPart.getDisposition()))) {
                        continue;
                    }

                    attachmentList.put(bodyPart.getFileName(), bodyPart.getInputStream());
                }

                List<String> toList = new ArrayList<String>();
                List<String> ccList = new ArrayList<String>();
                List<String> bccList = new ArrayList<String>();
                List<String> fromList = new ArrayList<String>();

                for (Address from : message.getFrom()) {
                    fromList.add(from.toString());
                }

                if ((message.getRecipients(RecipientType.TO) != null)
                        && (message.getRecipients(RecipientType.TO).length != 0)) {
                    for (Address to : message.getRecipients(RecipientType.TO)) {
                        toList.add(to.toString());
                    }
                }

                if ((message.getRecipients(RecipientType.CC) != null)
                        && (message.getRecipients(RecipientType.CC).length != 0)) {
                    for (Address cc : message.getRecipients(RecipientType.CC)) {
                        ccList.add(cc.toString());
                    }
                }

                if ((message.getRecipients(RecipientType.BCC) != null)
                        && (message.getRecipients(RecipientType.BCC).length != 0)) {
                    for (Address bcc : message.getRecipients(RecipientType.BCC)) {
                        bccList.add(bcc.toString());
                    }
                }

                EmailMessage emailMessage = new EmailMessage();
                emailMessage.setMessageTo(toList);
                emailMessage.setMessageCC(ccList);
                emailMessage.setMessageBCC(bccList);
                emailMessage.setEmailAddr(fromList);
                emailMessage.setMessageAttachments(attachmentList);
                emailMessage.setMessageDate(message.getSentDate());
                emailMessage.setMessageSubject(message.getSubject());
                emailMessage.setMessageBody(message.getContent().toString());
                emailMessage.setMessageSources(message.getHeader("Received"));

                if (DEBUG) {
                    DEBUGGER.debug("emailMessage: {}", emailMessage);
                }

                emailMessages.add(emailMessage);

                if (DEBUG) {
                    DEBUGGER.debug("emailMessages: {}", emailMessages);
                }
            }

            // archive it
            archiveFolder.open(Folder.READ_WRITE);

            if (archiveFolder.isOpen()) {
                mailFolder.copyMessages(new Message[] { message }, archiveFolder);
                message.setFlag(Flags.Flag.DELETED, true);
            }
        }
    } catch (IOException iox) {
        throw new MessagingException(iox.getMessage(), iox);
    } catch (MessagingException mex) {
        throw new MessagingException(mex.getMessage(), mex);
    } finally {
        try {
            if ((mailFolder != null) && (mailFolder.isOpen())) {
                mailFolder.close(true);
            }

            if ((archiveFolder != null) && (archiveFolder.isOpen())) {
                archiveFolder.close(false);
            }
        } catch (MessagingException mx) {
            ERROR_RECORDER.error(mx.getMessage(), mx);
        }
    }

    return emailMessages;
}

From source file:com.opinionlab.woa.Awesome.java

public Awesome(Message message) {
    try {// w w  w  .j  av  a 2 s . co m
        this.messageID = ((MimeMessage) message).getMessageID();
        this.id = ID_PTN.matcher(this.messageID).replaceAll("_");

        this.receivedDate = message.getReceivedDate();
        this.monthDay = DATE_FORMATTER
                .format(LocalDateTime.ofInstant(receivedDate.toInstant(), systemDefault()));
        this.to = new Person((InternetAddress) //todo Do this smarter
        message.getRecipients(Message.RecipientType.TO)[0]);
        this.from = new Person((InternetAddress) message.getFrom()[0]);
        this.subject = message.getSubject();

        final MimeMessageParser parser = new MimeMessageParser((MimeMessage) message).parse();
        if (!parser.hasPlainContent()) {
            LOGGER.error(format("Unable to parse message '%s'; has no plain content", this.messageID));
            this.comment = "Unknown content.";
        } else {
            this.comment = parseContent(parser.getPlainContent());
        }
    } catch (Throwable t) {
        throw new IllegalArgumentException(t);
    }
}

From source file:com.ikon.util.MailUtils.java

/**
 * Import messages/*from   w  w  w.jav  a  2 s.c  o  m*/
 * http://www.jguru.com/faq/view.jsp?EID=26898
 * 
 * == Using Unique Identifier (UIDL) ==
 * Mail server assigns an unique identifier for every email in the same account. You can get as UIDL
 * for every email by MailInfo.UIDL property. To avoid receiving the same email twice, the best way is
 * storing the UIDL of email retrieved to a text file or database. Next time before you retrieve email,
 * compare your local uidl list with remote uidl. If this uidl exists in your local uidl list, don't
 * receive it; otherwise receive it.
 * 
 * == Different property of UIDL in POP3 and IMAP4 ==
 * UIDL is always unique in IMAP4 and it is always an incremental integer. UIDL in POP3 can be any valid
 * asc-ii characters, and an UIDL may be reused by POP3 server if email with this UIDL has been deleted
 * from the server. Hence you are advised to remove the uidl from your local uidl list if that uidl is
 * no longer exist on the POP3 server.
 * 
 * == Remarks ==
 * You should create different local uidl list for different email account, because the uidl is only
 * unique for the same account.
 */
public static String importMessages(String token, MailAccount ma) throws PathNotFoundException,
        ItemExistsException, VirusDetectedException, AccessDeniedException, RepositoryException,
        DatabaseException, UserQuotaExceededException, ExtensionException, AutomationException {
    log.debug("importMessages({}, {})", new Object[] { token, ma });
    Session session = Session.getDefaultInstance(getProperties());
    String exceptionMessage = null;

    try {
        // Open connection
        Store store = session.getStore(ma.getMailProtocol());
        store.connect(ma.getMailHost(), ma.getMailUser(), ma.getMailPassword());

        Folder folder = store.getFolder(ma.getMailFolder());
        folder.open(Folder.READ_WRITE);
        Message messages[] = null;

        if (folder instanceof IMAPFolder) {
            // IMAP folder UIDs begins at 1 and are supposed to be sequential.
            // Each folder has its own UIDs sequence, not is a global one.
            messages = ((IMAPFolder) folder).getMessagesByUID(ma.getMailLastUid() + 1, UIDFolder.LASTUID);
        } else {
            messages = folder.search(new FlagTerm(new Flags(Flags.Flag.SEEN), false));
        }

        for (int i = 0; i < messages.length; i++) {
            Message msg = messages[i];
            log.info(i + ": " + msg.getFrom()[0] + " " + msg.getSubject() + " " + msg.getContentType());
            log.info("Received: " + msg.getReceivedDate());
            log.info("Sent: " + msg.getSentDate());
            log.debug("{} -> {} - {}", new Object[] { i, msg.getSubject(), msg.getReceivedDate() });
            com.ikon.bean.Mail mail = messageToMail(msg);

            if (ma.getMailFilters().isEmpty()) {
                log.debug("Import in compatibility mode");
                String mailPath = getUserMailPath(ma.getUser());
                importMail(token, mailPath, true, folder, msg, ma, mail);
            } else {
                for (MailFilter mf : ma.getMailFilters()) {
                    log.debug("MailFilter: {}", mf);

                    if (checkRules(mail, mf.getFilterRules())) {
                        String mailPath = mf.getPath();
                        importMail(token, mailPath, mf.isGrouping(), folder, msg, ma, mail);
                    }
                }
            }

            // Set message as seen
            if (ma.isMailMarkSeen()) {
                msg.setFlag(Flags.Flag.SEEN, true);
            } else {
                msg.setFlag(Flags.Flag.SEEN, false);
            }

            // Delete read mail if requested
            if (ma.isMailMarkDeleted()) {
                msg.setFlag(Flags.Flag.DELETED, true);
            }

            // Set lastUid
            if (folder instanceof IMAPFolder) {
                long msgUid = ((IMAPFolder) folder).getUID(msg);
                log.info("Message UID: {}", msgUid);
                ma.setMailLastUid(msgUid);
                MailAccountDAO.update(ma);
            }
        }

        // Close connection
        log.debug("Expunge: {}", ma.isMailMarkDeleted());
        folder.close(ma.isMailMarkDeleted());
        store.close();
    } catch (NoSuchProviderException e) {
        log.error(e.getMessage(), e);
        exceptionMessage = e.getMessage();
    } catch (MessagingException e) {
        log.error(e.getMessage(), e);
        exceptionMessage = e.getMessage();
    } catch (IOException e) {
        log.error(e.getMessage(), e);
        exceptionMessage = e.getMessage();
    }

    log.debug("importMessages: {}", exceptionMessage);
    return exceptionMessage;
}

From source file:com.seleniumtests.connectors.mails.ImapClient.java

/**
 * get list of all emails in folder/*from   ww w.  j av a2 s.co  m*/
 * 
 * @param folderName      folder to read
 * @param firstMessageTime   date from which we should get messages
 * @param firstMessageIndex index of the firste message to find
 * @throws MessagingException
 * @throws IOException
 */
@Override
public List<Email> getEmails(String folderName, int firstMessageIndex, LocalDateTime firstMessageTime)
        throws MessagingException, IOException {

    if (folderName == null) {
        throw new MessagingException("folder ne doit pas tre vide");
    }

    // Get folder
    Folder folder = store.getFolder(folderName);
    folder.open(Folder.READ_ONLY);

    // Get directory
    Message[] messages = folder.getMessages();

    List<Message> preFilteredMessages = new ArrayList<>();

    final LocalDateTime firstTime = firstMessageTime;

    // on filtre les message en fonction du mode de recherche
    if (searchMode == SearchMode.BY_INDEX || firstTime == null) {
        for (int i = firstMessageIndex, n = messages.length; i < n; i++) {
            preFilteredMessages.add(messages[i]);
        }
    } else {
        preFilteredMessages = Arrays.asList(folder.search(new SearchTerm() {
            private static final long serialVersionUID = 1L;

            @Override
            public boolean match(Message msg) {
                try {
                    return !msg.getReceivedDate()
                            .before(Date.from(firstTime.atZone(ZoneId.systemDefault()).toInstant()));
                } catch (MessagingException e) {
                    return false;
                }
            }
        }));

    }

    List<Email> filteredEmails = new ArrayList<>();
    lastMessageIndex = messages.length;

    for (Message message : preFilteredMessages) {

        String contentType = "";
        try {
            contentType = message.getContentType();
        } catch (MessagingException e) {
            MimeMessage msg = (MimeMessage) message;
            message = new MimeMessage(msg);
            contentType = message.getContentType();
        }

        // decode content
        String messageContent = "";
        List<String> attachments = new ArrayList<>();

        if (contentType.toLowerCase().contains("text/html")) {
            messageContent += StringEscapeUtils.unescapeHtml4(message.getContent().toString());
        } else if (contentType.toLowerCase().contains("multipart/")) {
            List<BodyPart> partList = getMessageParts((Multipart) message.getContent());

            // store content in list
            for (BodyPart part : partList) {

                String partContentType = part.getContentType().toLowerCase();
                if (partContentType.contains("text/html")) {
                    messageContent = messageContent
                            .concat(StringEscapeUtils.unescapeHtml4(part.getContent().toString()));

                } else if (partContentType.contains("text/") && !partContentType.contains("vcard")) {
                    messageContent = messageContent.concat((String) part.getContent().toString());

                } else if (partContentType.contains("image") || partContentType.contains("application/")
                        || partContentType.contains("text/x-vcard")) {
                    if (part.getFileName() != null) {
                        attachments.add(part.getFileName());
                    } else {
                        attachments.add(part.getDescription());
                    }
                } else {
                    logger.debug("type: " + part.getContentType());
                }
            }
        }

        // create a new email
        filteredEmails.add(new Email(message.getSubject(), messageContent, "",
                message.getReceivedDate().toInstant().atZone(ZoneId.systemDefault()).toLocalDateTime(),
                attachments));
    }

    folder.close(false);

    return filteredEmails;
}

From source file:com.ikon.util.MailUtils.java

/**
 * Convert Mime Message to Mail/*from   ww  w  .  j a va  2s. c  o  m*/
 */
public static Mail messageToMail(Message msg) throws MessagingException, IOException {
    com.ikon.bean.Mail mail = new com.ikon.bean.Mail();
    Calendar receivedDate = Calendar.getInstance();
    Calendar sentDate = Calendar.getInstance();

    // Can be void
    if (msg.getReceivedDate() != null) {
        receivedDate.setTime(msg.getReceivedDate());
    }

    // Can be void
    if (msg.getSentDate() != null) {
        sentDate.setTime(msg.getSentDate());
    }

    String body = getText(msg);

    // log.info("getText: "+body);
    if (body.charAt(0) == 'H') {
        mail.setMimeType(MimeTypeConfig.MIME_HTML);
    } else if (body.charAt(0) == 'T') {
        mail.setMimeType(MimeTypeConfig.MIME_TEXT);
    } else {
        mail.setMimeType(MimeTypeConfig.MIME_UNDEFINED);
    }

    String content = body.substring(1);

    // Need to replace 0x00 because PostgreSQL does not accept string containing 0x00
    content = FormatUtil.fixUTF8(content);

    // Need to remove Unicode surrogate because of MySQL => SQL Error: 1366, SQLState: HY000
    content = FormatUtil.trimUnicodeSurrogates(content);

    mail.setContent(content);

    if (msg.getFrom().length > 0) {
        mail.setFrom(MimeUtility.decodeText(msg.getFrom()[0].toString()));
    }

    mail.setSize(msg.getSize());
    mail.setSubject((msg.getSubject() == null || msg.getSubject().isEmpty()) ? NO_SUBJECT : msg.getSubject());
    mail.setTo(addressToString(msg.getRecipients(Message.RecipientType.TO)));
    mail.setCc(addressToString(msg.getRecipients(Message.RecipientType.CC)));
    mail.setBcc(addressToString(msg.getRecipients(Message.RecipientType.BCC)));
    mail.setReceivedDate(receivedDate);
    mail.setSentDate(sentDate);

    return mail;
}

From source file:pt.lsts.neptus.comm.iridium.RockBlockIridiumMessenger.java

@Override
public Collection<IridiumMessage> pollMessages(Date timeSince) throws Exception {

    if (askGmailPassword || gmailPassword == null || gmailUsername == null) {
        Pair<String, String> credentials = GuiUtils.askCredentials(ConfigFetch.getSuperParentFrame(),
                "Enter Gmail Credentials", getGmailUsername(), getGmailPassword());
        if (credentials == null)
            return null;
        setGmailUsername(credentials.first());
        setGmailPassword(credentials.second());
        PluginUtils.saveProperties("conf/rockblock.props", this);
        askGmailPassword = false;/*from  w ww  .  java  2 s.co  m*/
    }

    Properties props = new Properties();
    props.put("mail.store.protocol", "imaps");
    ArrayList<IridiumMessage> messages = new ArrayList<>();
    try {
        Session session = Session.getDefaultInstance(props, null);
        Store store = session.getStore("imaps");
        store.connect("imap.gmail.com", getGmailUsername(), getGmailPassword());

        Folder inbox = store.getFolder("Inbox");
        inbox.open(Folder.READ_ONLY);
        int numMsgs = inbox.getMessageCount();

        for (int i = numMsgs; i > 0; i--) {
            Message m = inbox.getMessage(i);
            if (m.getReceivedDate().before(timeSince)) {
                break;
            } else {
                MimeMultipart mime = (MimeMultipart) m.getContent();
                for (int j = 0; j < mime.getCount(); j++) {
                    BodyPart p = mime.getBodyPart(j);
                    Matcher matcher = pattern.matcher(p.getContentType());
                    if (matcher.matches()) {
                        InputStream stream = (InputStream) p.getContent();
                        byte[] data = IOUtils.toByteArray(stream);
                        IridiumMessage msg = process(data, matcher.group(1));
                        if (msg != null)
                            messages.add(msg);
                    }
                }
            }
        }
    } catch (NoSuchProviderException ex) {
        ex.printStackTrace();
        System.exit(1);
    } catch (MessagingException ex) {
        ex.printStackTrace();
        System.exit(2);
    }

    return messages;
}

From source file:com.openkm.util.MailUtils.java

/**
 * Convert Mime Message to Mail/*from w  ww .ja  va 2 s. co m*/
 */
public static Mail messageToMail(Message msg) throws MessagingException, IOException {
    com.openkm.bean.Mail mail = new com.openkm.bean.Mail();
    Calendar receivedDate = Calendar.getInstance();
    Calendar sentDate = Calendar.getInstance();

    // Can be void
    if (msg.getReceivedDate() != null) {
        receivedDate.setTime(msg.getReceivedDate());
    }

    // Can be void
    if (msg.getSentDate() != null) {
        sentDate.setTime(msg.getSentDate());
    }

    String body = getText(msg);

    // log.info("getText: "+body);
    if (body.charAt(0) == 'H') {
        mail.setMimeType(MimeTypeConfig.MIME_HTML);
    } else if (body.charAt(0) == 'T') {
        mail.setMimeType(MimeTypeConfig.MIME_TEXT);
    } else {
        mail.setMimeType(MimeTypeConfig.MIME_UNDEFINED);
    }

    if (msg.getFrom() != null && msg.getFrom().length > 0) {
        mail.setFrom(addressToString(msg.getFrom()[0]));
    }

    mail.setSize(msg.getSize());
    mail.setContent(body.substring(1));
    mail.setSubject((msg.getSubject() == null || msg.getSubject().isEmpty()) ? NO_SUBJECT : msg.getSubject());
    mail.setTo(addressToString(msg.getRecipients(Message.RecipientType.TO)));
    mail.setCc(addressToString(msg.getRecipients(Message.RecipientType.CC)));
    mail.setBcc(addressToString(msg.getRecipients(Message.RecipientType.BCC)));
    mail.setReceivedDate(receivedDate);
    mail.setSentDate(sentDate);

    return mail;
}

From source file:com.openkm.util.MailUtils.java

/**
 * Import messages//from   w  w w  . j a v a 2s  .c  o  m
 * http://www.jguru.com/faq/view.jsp?EID=26898
 * 
 * == Using Unique Identifier (UIDL) ==
 * Mail server assigns an unique identifier for every email in the same account. You can get as UIDL
 * for every email by MailInfo.UIDL property. To avoid receiving the same email twice, the best way is
 * storing the UIDL of email retrieved to a text file or database. Next time before you retrieve email,
 * compare your local uidl list with remote uidl. If this uidl exists in your local uidl list, don't
 * receive it; otherwise receive it.
 * 
 * == Different property of UIDL in POP3 and IMAP4 ==
 * UIDL is always unique in IMAP4 and it is always an incremental integer. UIDL in POP3 can be any valid
 * asc-ii characters, and an UIDL may be reused by POP3 server if email with this UIDL has been deleted
 * from the server. Hence you are advised to remove the uidl from your local uidl list if that uidl is
 * no longer exist on the POP3 server.
 * 
 * == Remarks ==
 * You should create different local uidl list for different email account, because the uidl is only
 * unique for the same account.
 */
public static String importMessages(String token, MailAccount ma) throws PathNotFoundException,
        ItemExistsException, VirusDetectedException, AccessDeniedException, RepositoryException,
        DatabaseException, UserQuotaExceededException, ExtensionException, AutomationException {
    log.debug("importMessages({}, {})", new Object[] { token, ma });
    Session session = Session.getDefaultInstance(getProperties());
    String exceptionMessage = null;

    try {
        // Open connection
        Store store = session.getStore(ma.getMailProtocol());
        store.connect(ma.getMailHost(), ma.getMailUser(), ma.getMailPassword());

        Folder folder = store.getFolder(ma.getMailFolder());
        folder.open(Folder.READ_WRITE);
        Message messages[] = null;

        if (folder instanceof IMAPFolder) {
            // IMAP folder UIDs begins at 1 and are supposed to be sequential.
            // Each folder has its own UIDs sequence, not is a global one.
            messages = ((IMAPFolder) folder).getMessagesByUID(ma.getMailLastUid() + 1, UIDFolder.LASTUID);
        } else {
            messages = folder.search(new FlagTerm(new Flags(Flags.Flag.SEEN), false));
        }

        for (int i = 0; i < messages.length; i++) {
            Message msg = messages[i];
            log.info("======= ======= {} ======= =======", i);
            log.info("Subject: {}", msg.getSubject());
            log.info("From: {}", msg.getFrom());
            log.info("Received: {}", msg.getReceivedDate());
            log.info("Sent: {}", msg.getSentDate());
            com.openkm.bean.Mail mail = messageToMail(msg);

            if (ma.getMailFilters().isEmpty()) {
                log.debug("Import in compatibility mode");
                String mailPath = getUserMailPath(ma.getUser());
                importMail(token, mailPath, true, folder, msg, ma, mail);
            } else {
                for (MailFilter mf : ma.getMailFilters()) {
                    log.debug("MailFilter: {}", mf);

                    if (checkRules(mail, mf.getFilterRules())) {
                        String mailPath = mf.getPath();
                        importMail(token, mailPath, mf.isGrouping(), folder, msg, ma, mail);
                    }
                }
            }

            // Set message as seen
            if (ma.isMailMarkSeen()) {
                msg.setFlag(Flags.Flag.SEEN, true);
            } else {
                msg.setFlag(Flags.Flag.SEEN, false);
            }

            // Delete read mail if requested
            if (ma.isMailMarkDeleted()) {
                msg.setFlag(Flags.Flag.DELETED, true);
            }

            // Set lastUid
            if (folder instanceof IMAPFolder) {
                long msgUid = ((IMAPFolder) folder).getUID(msg);
                log.info("Message UID: {}", msgUid);
                ma.setMailLastUid(msgUid);
                MailAccountDAO.update(ma);
            }
        }

        // Close connection
        log.debug("Expunge: {}", ma.isMailMarkDeleted());
        folder.close(ma.isMailMarkDeleted());
        store.close();
    } catch (NoSuchProviderException e) {
        log.error(e.getMessage(), e);
        exceptionMessage = e.getMessage();
    } catch (MessagingException e) {
        log.error(e.getMessage(), e);
        exceptionMessage = e.getMessage();
    } catch (IOException e) {
        log.error(e.getMessage(), e);
        exceptionMessage = e.getMessage();
    }

    log.debug("importMessages: {}", exceptionMessage);
    return exceptionMessage;
}

From source file:EmailBean.java

private void displayMessage(Message msg, PrintWriter out) throws MessagingException, IOException {

    if (msg != null && msg.getContent() instanceof String) {

        if (msg.getFrom()[0] instanceof InternetAddress) {
            out.println(//from ww w  .  j ava2s.  c o  m
                    "Message received from: " + ((InternetAddress) msg.getFrom()[0]).getAddress() + "<br />");
        }
        out.println("Message received on: " + msg.getReceivedDate() + "<br />");
        out.println("Message content type: " + msg.getContentType() + "<br />");
        out.println("Message content type: " + (String) msg.getContent());
    } else {

        out.println("<h2>The received email message was not of a text content type.</h2>");

    }

}

From source file:org.zilverline.core.IMAPCollection.java

/**
 * Index one message./*from w  w  w. j a v  a2  s.c  om*/
 */
private void indexMessage(final Document doc, final Message m) throws MessagingException, IOException {
    if (stopRequested) {
        log.info("Indexing stops, due to request");
        return;
    }
    final long uid = ((UIDFolder) m.getFolder()).getUID(m);

    // form a URL that mozilla seems to accept. Couldn't get it to accept
    // what I thought was the standard

    String urlPrefix = "imap://" + user + "@" + host + ":143/fetch%3EUID%3E/";

    final String url = urlPrefix + m.getFolder().getFullName() + "%3E" + uid;
    doc.add(Field.Text("name", url));

    final String subject = m.getSubject();
    final Date recv = m.getReceivedDate();
    final Date sent = m.getSentDate();
    log.info("Folder: " + m.getFolder().getFullName() + ": Message received " + recv + ", subject: " + subject);
    // -------------------------------------------------------
    // data gathered, now add to doc

    if (subject != null) {
        doc.add(Field.Text(F_SUBJECT, m.getSubject()));
        doc.add(Field.Text("title", m.getSubject()));
    }

    if (recv != null) {
        doc.add(Field.Keyword(F_RECEIVED, DateTools.timeToString(recv.getTime(), DateTools.Resolution.SECOND)));
    }

    if (sent != null) {
        doc.add(Field.Keyword(F_SENT, DateTools.timeToString(sent.getTime(), DateTools.Resolution.SECOND)));
        // store date as yyyyMMdd
        DateFormat df = new SimpleDateFormat("yyyyMMdd");
        String dfString = df.format(new Date(sent.getTime()));
        doc.add(Field.Keyword("modified", dfString));
    }

    doc.add(Field.Keyword(F_URL, url));

    Address[] addrs = m.getAllRecipients();
    if (addrs != null) {
        for (int j = 0; j < addrs.length; j++) {
            doc.add(Field.Keyword(F_TO, "" + addrs[j]));
        }
    }

    addrs = m.getFrom();
    if (addrs != null) {
        for (int j = 0; j < addrs.length; j++) {
            doc.add(Field.Keyword(F_FROM, "" + addrs[j]));
            doc.add(Field.Keyword("author", "" + addrs[j]));
        }
    }
    addrs = m.getReplyTo();
    if (addrs != null) {
        for (int j = 0; j < addrs.length; j++) {
            doc.add(Field.Keyword(F_REPLY_TO, "" + addrs[j]));
        }
    }

    doc.add(Field.Keyword(F_UID, "" + uid));

    // could ignore docs that have the deleted flag set
    for (int j = 0; j < FLAGS.length; j++) {
        boolean val = m.isSet(FLAGS[j]);
        doc.add(Field.Keyword(SFLAGS[j], (val ? "true" : "false")));
    }

    // now special case for mime
    if (m instanceof MimeMessage) {
        // mime++;
        MimeMessage mm = (MimeMessage) m;
        log.debug("index, adding MimeMessage " + m.getFileName());
        indexMimeMessage(doc, mm);

    } else {
        // nmime++;

        final DataHandler dh = m.getDataHandler();
        log.debug("index, adding (non-MIME) Content " + m.getFileName());
        doc.add(Field.Text(F_CONTENTS, new InputStreamReader(dh.getInputStream())));
    }
}