Example usage for javax.mail Message getSentDate

List of usage examples for javax.mail Message getSentDate

Introduction

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

Prototype

public abstract Date getSentDate() throws MessagingException;

Source Link

Document

Get the date this message was sent.

Usage

From source file:com.naryx.tagfusion.cfm.mail.cfPOP3.java

private void populateMessage(cfSession _Session, Message thisMessage, cfQueryResultData popData, boolean GetAll,
        File attachmentDir, Folder _parent) throws Exception {
    popData.addRow(1);//from   ww  w.  ja v  a 2s . c o  m
    int Row = popData.getNoRows();

    Date date = thisMessage.getSentDate();
    if (date != null) {
        cfDateData cfdate = new cfDateData(date);
        cfdate.setPOPDate();
        popData.setCell(Row, 1, cfdate);
    } else {
        popData.setCell(Row, 1, new cfStringData(""));
    }

    popData.setCell(Row, 2, new cfStringData(formatAddress(thisMessage.getFrom())));
    popData.setCell(Row, 3, new cfNumberData(thisMessage.getMessageNumber()));
    popData.setCell(Row, 4, new cfStringData(formatAddress(thisMessage.getReplyTo())));
    popData.setCell(Row, 5, new cfStringData(thisMessage.getSubject()));
    popData.setCell(Row, 6,
            new cfStringData(formatAddress(thisMessage.getRecipients(Message.RecipientType.CC))));
    popData.setCell(Row, 7,
            new cfStringData(formatAddress(thisMessage.getRecipients(Message.RecipientType.TO))));
    String[] msgid = thisMessage.getHeader("Message-ID");
    popData.setCell(Row, 8, new cfStringData(msgid != null ? msgid[0] : ""));
    popData.setCell(Row, 9, new cfStringData(getMessageUID(_parent, thisMessage)));
    popData.setCell(Row, 10, new cfStringData(formatHeader(thisMessage)));

    if (GetAll) {
        retrieveBody(_Session, thisMessage, popData, Row, attachmentDir);
    }
}

From source file:de.kp.ames.web.function.access.imap.ImapConsumer.java

/**
 * Retrieve mail messages in a JSON representation
 * /*from   w w  w. j  a  v  a  2s .  c  o  m*/
 * @return
 */
public JSONArray getJMessages() {

    JSONArray jMessages = new JSONArray();
    if (store == null)
        return jMessages;

    try {
        /*
         * Connect to IMAP store
         */
        store.connect();

        /*
         * Retrieve & open INBOX folder
         */
        Folder folder = store.getFolder(ImapConstants.INBOX);
        folder.open(Folder.READ_ONLY);

        Message[] messages = folder.getMessages();
        for (int i = 0; i < messages.length; i++) {

            Message m = messages[i];

            JSONObject jMessage = new JSONObject();

            jMessage.put(ImapConstants.J_KEY, ""); // introduced to be compatible with posted emails             
            jMessage.put(ImapConstants.J_ID, i); // message identifier to retrieve from external server

            jMessage.put(ImapConstants.J_SUBJECT, m.getSubject());
            jMessage.put(ImapConstants.J_DATE, m.getSentDate());

            String from = "";

            Address[] addresses = m.getFrom();
            for (Address address : addresses) {

                InternetAddress internetAddress = (InternetAddress) address;
                from = internetAddress.getPersonal();

            }

            jMessage.put(ImapConstants.J_FROM, from);

            FileUtil attachment = getAttachment(m);
            if (attachment == null) {
                jMessage.put(ImapConstants.J_ATTACHMENT, false);

            } else {
                jMessage.put(ImapConstants.J_ATTACHMENT, true);

            }

            jMessages.put(jMessages.length(), jMessage);

        }

        folder.close(false);
        store.close();

    } catch (Exception e) {
        e.printStackTrace();

    } finally {
    }

    return jMessages;
}

From source file:com.cubusmail.server.mail.util.MessageComparator.java

public int compare(Message msg1, Message msg2) {

    int result = 0;

    if (msg1.isExpunged() || msg2.isExpunged()) {
        return result;
    }//from  w ww  . ja  v  a2  s.c  om

    try {
        if (MessageListFields.SUBJECT == this.field) {
            if (msg1.getSubject() != null && msg2.getSubject() != null) {
                result = msg1.getSubject().compareToIgnoreCase(msg2.getSubject());
            } else {
                result = -1;
            }
        } else if (MessageListFields.FROM == this.field) {
            String fromString1 = MessageUtils.getMailAdressString(msg1.getFrom(), AddressStringType.PERSONAL);
            String fromString2 = MessageUtils.getMailAdressString(msg2.getFrom(), AddressStringType.PERSONAL);
            if (fromString1 != null && fromString2 != null) {
                result = fromString1.compareToIgnoreCase(fromString2);
            } else {
                result = -1;
            }
        } else if (MessageListFields.SEND_DATE == this.field) {
            Date date1 = msg1.getSentDate();
            Date date2 = msg2.getSentDate();
            if (date1 != null && date2 != null) {
                result = date1.compareTo(date2);
            } else {
                result = -1;
            }
        } else if (MessageListFields.SIZE == this.field) {
            int size1 = msg1.getSize();
            int size2 = msg2.getSize();
            result = Integer.valueOf(size1).compareTo(Integer.valueOf(size2));

        }
    } catch (MessagingException e) {
        log.warn(e.getMessage(), e);
    }

    if (!this.ascending) {
        result = result * (-1);
    }

    return result;
}

From source file:com.crawlersick.nettool.GetattchmentFromMail1.java

public boolean fetchmailforattch() throws IOException, MessagingException {
    boolean fetchtest = false;

    Properties props = new Properties();
    props.setProperty("mail.store.protocol", "imaps");

    try {/*from  w  w  w  .  ja v  a 2s  .  co  m*/
        Session session = Session.getInstance(props, null);
        Store store = session.getStore();
        store.connect(IMapHost, MailId, MailPassword);
        Folder inbox = store.getFolder("INBOX");
        inbox.open(Folder.READ_ONLY);
        totalmailcount = inbox.getMessageCount();

        Message msg = null;
        for (int i = totalmailcount; i > 0; i--) {
            fromadd = "";
            msg = inbox.getMessage(i);
            Address[] in = msg.getFrom();
            for (Address address : in) {
                fromadd = address.toString() + fromadd;
                //System.out.println("FROM:" + address.toString());
            }
            if (fromadd.matches("admin@cronmailservice.appspotmail.com") && msg.getSubject().matches(
                    "ThanksToTsukuba_World-on-my-shoulders-as-I-run-back-to-this-8-Mile-Road_cronmailservice"))
                break;
        }

        if (fromadd.equals("'")) {
            log.log(Level.SEVERE, "Error: no related mail found!" + this.MailId);
            return fetchtest;
        }

        //    Multipart mp = (Multipart) msg.getContent();
        //  BodyPart bp = mp.getBodyPart(0);
        sentdate = msg.getSentDate().toString();

        subject = msg.getSubject();

        Content = msg.getContent().toString();

        log.log(Level.INFO, Content);
        log.log(Level.INFO, sentdate);
        localIntent.putExtra("213123", "Got Server latest update at : " + sentdate + " , Reading the Data...");
        LocalBroadcastManager.getInstance(myis).sendBroadcast(localIntent);

        Multipart multipart = (Multipart) msg.getContent();
        for (int i = 0; i < multipart.getCount(); i++) {
            BodyPart bodyPart = multipart.getBodyPart(i);
            if (!Part.ATTACHMENT.equalsIgnoreCase(bodyPart.getDisposition()) && (bodyPart.getFileName() == null
                    || !bodyPart.getFileName().equals("dataforvgendwithudp.gzip"))) {
                continue; // dealing with attachments only
            }
            ByteArrayOutputStream buffer = new ByteArrayOutputStream();
            InputStream is = bodyPart.getInputStream();
            //validvgbinary = IOUtils.toByteArray(is);
            int nRead;
            byte[] data = new byte[5000000];

            while ((nRead = is.read(data, 0, data.length)) != -1) {
                buffer.write(data, 0, nRead);
            }

            buffer.flush();

            validvgbinary = buffer.toByteArray();
            break;
        }

        fetchtest = true;
    } catch (Exception mex) {
        mex.printStackTrace();

    }

    return fetchtest;
}

From source file:de.saly.elasticsearch.support.IndexableMailMessage.java

public static IndexableMailMessage fromJavaMailMessage(final Message jmm, final boolean withTextContent,
        final boolean withAttachments, final boolean stripTags, List<String> headersToFields)
        throws MessagingException, IOException {
    final IndexableMailMessage im = new IndexableMailMessage();

    @SuppressWarnings("unchecked")
    final Enumeration<Header> allHeaders = jmm.getAllHeaders();

    final Set<IndexableHeader> headerList = new HashSet<IndexableHeader>();
    while (allHeaders.hasMoreElements()) {
        final Header h = allHeaders.nextElement();
        headerList.add(new IndexableHeader(h.getName(), h.getValue()));
    }/*www .ja v a2s  .  co m*/

    im.setHeaders(headerList.toArray(new IndexableHeader[headerList.size()]));

    im.setSelectedHeaders(extractHeaders(im.getHeaders(), headersToFields));

    if (jmm.getFolder() instanceof POP3Folder) {
        im.setPopId(((POP3Folder) jmm.getFolder()).getUID(jmm));
        im.setMailboxType("POP");

    } else {
        im.setMailboxType("IMAP");
    }

    if (jmm.getFolder() instanceof UIDFolder) {
        im.setUid(((UIDFolder) jmm.getFolder()).getUID(jmm));
    }

    im.setFolderFullName(jmm.getFolder().getFullName());

    im.setFolderUri(jmm.getFolder().getURLName().toString());

    im.setContentType(jmm.getContentType());
    im.setSubject(jmm.getSubject());
    im.setSize(jmm.getSize());
    im.setSentDate(jmm.getSentDate());

    if (jmm.getReceivedDate() != null) {
        im.setReceivedDate(jmm.getReceivedDate());
    }

    if (jmm.getFrom() != null && jmm.getFrom().length > 0) {
        im.setFrom(Address.fromJavaMailAddress(jmm.getFrom()[0]));
    }

    if (jmm.getRecipients(RecipientType.TO) != null) {
        im.setTo(Address.fromJavaMailAddress(jmm.getRecipients(RecipientType.TO)));
    }

    if (jmm.getRecipients(RecipientType.CC) != null) {
        im.setCc(Address.fromJavaMailAddress(jmm.getRecipients(RecipientType.CC)));
    }

    if (jmm.getRecipients(RecipientType.BCC) != null) {
        im.setBcc(Address.fromJavaMailAddress(jmm.getRecipients(RecipientType.BCC)));
    }

    if (withTextContent) {

        // try {

        String textContent = getText(jmm, 0);

        if (stripTags) {
            textContent = stripTags(textContent);
        }

        im.setTextContent(textContent);
        // } catch (final Exception e) {
        // logger.error("Unable to retrieve text content for message {} due to {}",
        // e, ((MimeMessage) jmm).getMessageID(), e);
        // }
    }

    if (withAttachments) {

        try {
            final Object content = jmm.getContent();

            // look for attachments
            if (jmm.isMimeType("multipart/*") && content instanceof Multipart) {
                List<ESAttachment> attachments = new ArrayList<ESAttachment>();

                final Multipart multipart = (Multipart) content;

                for (int i = 0; i < multipart.getCount(); i++) {
                    final BodyPart bodyPart = multipart.getBodyPart(i);
                    if (!Part.ATTACHMENT.equalsIgnoreCase(bodyPart.getDisposition())
                            && !StringUtils.isNotBlank(bodyPart.getFileName())) {
                        continue; // dealing with attachments only
                    }
                    final InputStream is = bodyPart.getInputStream();
                    final byte[] bytes = IOUtils.toByteArray(is);
                    IOUtils.closeQuietly(is);
                    attachments.add(new ESAttachment(bodyPart.getContentType(), bytes, bodyPart.getFileName()));
                }

                if (!attachments.isEmpty()) {
                    im.setAttachments(attachments.toArray(new ESAttachment[attachments.size()]));
                    im.setAttachmentCount(im.getAttachments().length);
                    attachments.clear();
                    attachments = null;
                }

            }
        } catch (final Exception e) {
            logger.error(
                    "Error indexing attachments (message will be indexed but without attachments) due to {}", e,
                    e.toString());
        }

    }

    im.setFlags(IMAPUtils.toStringArray(jmm.getFlags()));
    im.setFlaghashcode(jmm.getFlags().hashCode());

    return im;
}

From source file:org.exist.xquery.modules.mail.MessageListFunctions.java

private Sequence getMessageListAsXML(Sequence[] args, Sequence contextSequence) throws XPathException {
    Message[] msgList;//  w  ww.  j  a v  a2 s  . co m
    Sequence ret = Sequence.EMPTY_SEQUENCE;

    // was a msgList handle specified?
    if (args[0].isEmpty()) {
        throw (new XPathException(this, "Message List handle not specified"));
    }

    // get the MessageList
    long msgListHandle = ((IntegerValue) args[0].itemAt(0)).getLong();
    msgList = MailModule.retrieveMessageList(context, msgListHandle);
    if (msgList == null) {
        throw (new XPathException(this, "Invalid Message List handle specified"));
    }

    if (msgList.length > 0) {

        boolean includeHeaders = args[1].effectiveBooleanValue();

        MemTreeBuilder builder = context.getDocumentBuilder();

        builder.startDocument();
        builder.startElement(new QName("messages", MailModule.NAMESPACE_URI, MailModule.PREFIX), null);
        builder.addAttribute(new QName("count", null, null), String.valueOf(msgList.length));

        try {
            for (int i = 0; i < msgList.length; i++) {
                Message message = msgList[i];

                builder.startElement(new QName("message", MailModule.NAMESPACE_URI, MailModule.PREFIX), null);

                builder.addAttribute(new QName("number", null, null),
                        String.valueOf(message.getMessageNumber()));

                // Sent Date
                if (message.getSentDate() != null) {
                    builder.startElement(new QName("sent", MailModule.NAMESPACE_URI, MailModule.PREFIX), null);
                    builder.characters(formatDate(message.getSentDate()));
                    builder.endElement();
                }

                // Received Date
                if (message.getReceivedDate() != null) {
                    builder.startElement(new QName("received", MailModule.NAMESPACE_URI, MailModule.PREFIX),
                            null);
                    builder.characters(formatDate(message.getReceivedDate()));
                    builder.endElement();
                }

                // From
                if (message.getFrom() != null) {
                    builder.startElement(new QName("from", MailModule.NAMESPACE_URI, MailModule.PREFIX), null);
                    builder.characters(message.getFrom()[0].toString());
                    builder.endElement();
                }

                // Recipients
                builder.startElement(new QName("recipients", MailModule.NAMESPACE_URI, MailModule.PREFIX),
                        null);
                // To Recipients
                Address[] toAddresses = message.getRecipients(Message.RecipientType.TO);
                if (toAddresses != null) {
                    for (Address to : toAddresses) {
                        builder.startElement(
                                new QName("recipient", MailModule.NAMESPACE_URI, MailModule.PREFIX), null);
                        builder.addAttribute(new QName("type", null, null), "to");
                        builder.characters(to.toString());
                        builder.endElement();
                    }
                }

                // cc Recipients
                Address[] ccAddresses = message.getRecipients(Message.RecipientType.CC);
                if (ccAddresses != null) {
                    for (Address ccAddress : ccAddresses) {
                        builder.startElement(
                                new QName("recipient", MailModule.NAMESPACE_URI, MailModule.PREFIX), null);
                        builder.addAttribute(new QName("type", null, null), "cc");
                        builder.characters(ccAddress.toString());
                        builder.endElement();
                    }
                }

                // bcc Recipients
                Address[] bccAddresses = message.getRecipients(Message.RecipientType.BCC);
                if (bccAddresses != null) {
                    for (Address bccAddress : bccAddresses) {
                        builder.startElement(
                                new QName("recipient", MailModule.NAMESPACE_URI, MailModule.PREFIX), null);
                        builder.addAttribute(new QName("type", null, null), "bcc");
                        builder.characters(bccAddress.toString());
                        builder.endElement();
                    }
                }
                builder.endElement();

                // Flags

                Flags flags = message.getFlags();
                Flags.Flag[] systemFlags = flags.getSystemFlags();
                String[] userFlags = flags.getUserFlags();

                if (systemFlags.length > 0 || userFlags.length > 0) {
                    builder.startElement(new QName("flags", MailModule.NAMESPACE_URI, MailModule.PREFIX), null);

                    for (Flags.Flag systemFlag : systemFlags) {
                        if (systemFlag == Flags.Flag.ANSWERED) {
                            builder.startElement(new QName("flag", MailModule.NAMESPACE_URI, MailModule.PREFIX),
                                    null);
                            builder.addAttribute(new QName("type", null, null), "answered");
                            builder.endElement();
                        } else if (systemFlag == Flags.Flag.DELETED) {
                            builder.startElement(new QName("flag", MailModule.NAMESPACE_URI, MailModule.PREFIX),
                                    null);
                            builder.addAttribute(new QName("type", null, null), "deleted");
                            builder.endElement();
                        } else if (systemFlag == Flags.Flag.DRAFT) {
                            builder.startElement(new QName("flag", MailModule.NAMESPACE_URI, MailModule.PREFIX),
                                    null);
                            builder.addAttribute(new QName("type", null, null), "draft");
                            builder.endElement();
                        } else if (systemFlag == Flags.Flag.FLAGGED) {
                            builder.startElement(new QName("flag", MailModule.NAMESPACE_URI, MailModule.PREFIX),
                                    null);
                            builder.addAttribute(new QName("type", null, null), "flagged");
                            builder.endElement();
                        } else if (systemFlag == Flags.Flag.RECENT) {
                            builder.startElement(new QName("flag", MailModule.NAMESPACE_URI, MailModule.PREFIX),
                                    null);
                            builder.addAttribute(new QName("type", null, null), "recent");
                            builder.endElement();
                        } else if (systemFlag == Flags.Flag.SEEN) {
                            builder.startElement(new QName("flag", MailModule.NAMESPACE_URI, MailModule.PREFIX),
                                    null);
                            builder.addAttribute(new QName("type", null, null), "seen");
                            builder.endElement();
                        }
                    }

                    for (String userFlag : userFlags) {
                        builder.startElement(new QName("flag", MailModule.NAMESPACE_URI, MailModule.PREFIX),
                                null);
                        builder.addAttribute(new QName("type", null, null), "user");
                        builder.addAttribute(new QName("value", null, null), userFlag);
                        builder.endElement();
                    }

                    builder.endElement();
                }

                // Headers

                if (includeHeaders) {
                    Enumeration headers = message.getAllHeaders();

                    if (headers.hasMoreElements()) {
                        builder.startElement(new QName("headers", MailModule.NAMESPACE_URI, MailModule.PREFIX),
                                null);

                        while (headers.hasMoreElements()) {
                            Header header = (Header) headers.nextElement();

                            builder.startElement(
                                    new QName("header", MailModule.NAMESPACE_URI, MailModule.PREFIX), null);
                            builder.addAttribute(new QName("name", null, null), header.getName());
                            builder.addAttribute(new QName("value", null, null), header.getValue());
                            builder.endElement();
                        }

                        builder.endElement();
                    }
                }

                // Subject
                builder.startElement(new QName("subject", MailModule.NAMESPACE_URI, MailModule.PREFIX), null);
                builder.characters(message.getSubject());
                builder.endElement();

                builder.endElement();
            }
        } catch (MessagingException me) {
            throw (new XPathException(this, "Failed to retrieve messages from list", me));
        }

        builder.endElement();

        ret = (NodeValue) builder.getDocument().getDocumentElement();
    }

    return (ret);
}

From source file:nz.net.orcon.kanban.automation.actions.EmailReceiverAction.java

public void generateMailNotification(String mailStoreProtocol, String mailStoreHost, String mailStoreUserName,
        String mailStorePassword, String notificationType, String fromFilter, String subjectFilter)
        throws Exception {
    Session session = getMailStoreSession(mailStoreProtocol, mailStoreHost, mailStoreUserName,
            mailStorePassword);//from w  ww .  j  a  v a  2s  .  c  om
    try {
        // connects to the message store
        Store store = session.getStore(mailStoreProtocol);
        store.connect(mailStoreHost, mailStoreUserName, mailStorePassword);

        logger.info("connected to message store");

        // opens the inbox folder
        Folder folderInbox = store.getFolder("INBOX");
        folderInbox.open(Folder.READ_WRITE);

        // check if fromFilter is specified
        List<String> fromFilterList = null;

        if (StringUtils.isNotBlank(fromFilter)) {
            String[] fromFilterArray = StringUtils.split(fromFilter, "|");
            fromFilterList = Arrays.asList(fromFilterArray);
        }

        // check if subjectFilter is specified
        List<String> subjectFilterList = null;
        if (StringUtils.isNotBlank(subjectFilter)) {
            String[] subjectFilterArray = StringUtils.split(subjectFilter, "|");
            subjectFilterList = Arrays.asList(subjectFilterArray);
        }
        Map<String, Object> context = new HashMap<String, Object>();
        // fetches new messages from server
        Message[] messages = folderInbox.getMessages();
        for (int i = 0; i < messages.length; i++) {
            Message msg = messages[i];
            Address[] fromAddress = msg.getFrom();
            String address = fromAddress[0].toString();
            String from = extractFromAddress(address);
            if (StringUtils.isBlank(from)) {
                logger.warn("From Address is not proper " + from);
                return;
            }
            boolean isValidFrom = isValidMatch(fromFilterList, from);

            // filter based on fromFilter specified
            if (null == fromFilterList || isValidFrom) {
                String subject = msg.getSubject();

                boolean isValidSubject = isValidMatch(subjectFilterList, subject);
                if (null == subjectFilterList || isValidSubject) {
                    String toList = parseAddresses(msg.getRecipients(RecipientType.TO));
                    String ccList = parseAddresses(msg.getRecipients(RecipientType.CC));
                    String sentDate = msg.getSentDate().toString();

                    String messageContent = "";
                    try {
                        Object content = msg.getContent();
                        if (content != null) {
                            messageContent = content.toString();
                        }
                    } catch (Exception ex) {
                        messageContent = "[Error downloading content]";
                        ex.printStackTrace();
                    }
                    context.put("from", from);
                    context.put("to", toList);
                    context.put("cc", ccList);
                    context.put("subject", subject);
                    context.put("messagebody", messageContent);
                    context.put("sentdate", sentDate);

                    notificationController.createNotification(notificationType, context);
                    msg.setFlag(Flag.DELETED, true);
                } else {
                    logger.warn("subjectFilter doesn't match");
                }
            } else {
                logger.warn("this email originated from " + address
                        + " , which does not match fromAddress specified in the rule, it should be "
                        + fromFilter.toString());
            }
        }
        // disconnect and delete messages marked as DELETED
        folderInbox.close(true);
        store.close();
    } catch (NoSuchProviderException ex) {
        logger.warn("No provider for protocol: " + mailStoreProtocol + " " + ex);
    } catch (MessagingException ex) {
        logger.error("Could not connect to the message store" + ex);
    }
}

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

/**
 * Index one message.//  w ww. j  a  va2s.c  o  m
 */
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())));
    }
}

From source file:com.aquest.emailmarketing.web.service.BouncedEmailService.java

/**
 * Process bounces.//from  w  w w  .ja  v  a  2  s.c o  m
 *
 * @param protocol the protocol
 * @param host the host
 * @param port the port
 * @param userName the user name
 * @param password the password
 */
public void processBounces(String protocol, String host, String port, String userName, String password) {
    Properties properties = getServerProperties(protocol, host, port);
    Session session = Session.getDefaultInstance(properties);

    List<BounceCode> bounceCodes = bounceCodeService.getAllBounceCodes();

    try {
        // connects to the message store
        Store store = session.getStore(protocol);
        System.out.println(userName);
        System.out.println(password);
        System.out.println(userName.length());
        System.out.println(password.length());
        //store.connect(userName, password);
        //TODO: ispraviti username i password da idu iz poziva a ne hardcoded
        store.connect("bojan.dimic@aquest-solutions.com", "bg181076");

        // opens the inbox folder
        Folder folderInbox = store.getFolder("INBOX");
        folderInbox.open(Folder.READ_ONLY);

        // fetches new messages from server
        Message[] messages = folderInbox.getMessages();

        for (int i = 0; i < messages.length; i++) {
            BouncedEmail bouncedEmail = new BouncedEmail();
            Message msg = messages[i];
            Address[] fromAddress = msg.getFrom();
            String from = fromAddress[0].toString();
            String failedAddress = "";
            Enumeration<?> headers = messages[i].getAllHeaders();
            while (headers.hasMoreElements()) {
                Header h = (Header) headers.nextElement();
                //System.out.println(h.getName() + ":" + h.getValue());
                //System.out.println("");                
                String mID = h.getName();
                if (mID.contains("X-Failed-Recipients")) {
                    failedAddress = h.getValue();
                }
            }
            String subject = msg.getSubject();
            String toList = parseAddresses(msg.getRecipients(RecipientType.TO));
            String ccList = parseAddresses(msg.getRecipients(RecipientType.CC));
            String sentDate = msg.getSentDate().toString();

            String contentType = msg.getContentType();
            String messageContent = "";

            if (contentType.contains("text/plain") || contentType.contains("text/html")) {
                try {
                    Object content = msg.getContent();
                    if (content != null) {
                        messageContent = content.toString();
                    }
                } catch (Exception ex) {
                    messageContent = "[Error downloading content]";
                    ex.printStackTrace();
                }
            }

            String bounceReason = "Unknown reason";

            for (BounceCode bounceCode : bounceCodes) {
                if (messageContent.contains(bounceCode.getCode())) {
                    bounceReason = bounceCode.getExplanation();
                }
            }

            //                if(messageContent.contains(" 550 ") || messageContent.contains(" 550-")) {bounceReason="Users mailbox was unavailable (such as not found)";}
            //                if(messageContent.contains(" 554 ") || messageContent.contains(" 554-")) {bounceReason="The transaction failed for some unstated reason.";}
            //                
            //                // enhanced bounce codes
            //                if(messageContent.contains("5.0.0")) {bounceReason="Unknown issue";}
            //                if(messageContent.contains("5.1.0")) {bounceReason="Other address status";}
            //                if(messageContent.contains("5.1.1")) {bounceReason="Bad destination mailbox address";}
            //                if(messageContent.contains("5.1.2")) {bounceReason="Bad destination system address";}
            //                if(messageContent.contains("5.1.3")) {bounceReason="Bad destination mailbox address syntax";}
            //                if(messageContent.contains("5.1.4")) {bounceReason="Destination mailbox address ambiguous";}
            //                if(messageContent.contains("5.1.5")) {bounceReason="Destination mailbox address valid";}
            //                if(messageContent.contains("5.1.6")) {bounceReason="Mailbox has moved";}
            //                if(messageContent.contains("5.7.1")) {bounceReason="Delivery not authorized, message refused";}

            // print out details of each message
            System.out.println("Message #" + (i + 1) + ":");
            System.out.println("\t From: " + from);
            System.out.println("\t To: " + toList);
            System.out.println("\t CC: " + ccList);
            System.out.println("\t Subject: " + subject);
            System.out.println("\t Sent Date: " + sentDate);
            System.out.println("\t X-Failed-Recipients:" + failedAddress);
            System.out.println("\t Content Type:" + contentType);
            System.out.println("\t Bounce reason:" + bounceReason);
            //System.out.println("\t Message: " + messageContent);

            bouncedEmail.setEmail_address(failedAddress);
            bouncedEmail.setBounce_reason(bounceReason);

            //Date date = new Date();
            SimpleDateFormat formatter = new SimpleDateFormat("EEE MMM dd HH:mm:ss z yyyy", Locale.ENGLISH);
            SimpleDateFormat sqlFormat = new SimpleDateFormat("yyyy-mm-dd", Locale.ENGLISH);
            //String strDate = date.toString();
            System.out.println(sentDate);
            Date dt = null;
            //Date nd = null;
            try {
                dt = formatter.parse(sentDate);
                //nd = sqlFormat.parse(dt.toString());
            } catch (ParseException e) {
                e.printStackTrace();
            }
            System.out.println("Date " + dt.toString());
            //System.out.println("Date " + nd.toString());
            System.out.println(new Timestamp(new Date().getTime()));
            bouncedEmail.setSend_date(dt);
            bouncedEmailDao.saveOrUpdate(bouncedEmail);
        }

        // disconnect
        folderInbox.close(false);
        store.close();
    } catch (NoSuchProviderException ex) {
        System.out.println("No provider for protocol: " + protocol);
        ex.printStackTrace();
    } catch (MessagingException ex) {
        System.out.println("Could not connect to the message store");
        ex.printStackTrace();
    }
}

From source file:com.liferay.mail.imap.IMAPAccessor.java

public void storeEnvelopes(long folderId, Folder jxFolder, Message[] jxMessages) throws PortalException {

    StopWatch stopWatch = new StopWatch();

    stopWatch.start();/*from www  . j  a v  a2  s .c  om*/

    try {
        FetchProfile fetchProfile = new FetchProfile();

        fetchProfile.add(UIDFolder.FetchProfileItem.ENVELOPE);
        fetchProfile.add(UIDFolder.FetchProfileItem.FLAGS);
        fetchProfile.add(UIDFolder.FetchProfileItem.UID);

        jxFolder.fetch(jxMessages, fetchProfile);

        for (Message jxMessage : jxMessages) {
            String sender = InternetAddressUtil.toString(jxMessage.getFrom());
            String to = InternetAddressUtil.toString(jxMessage.getRecipients(RecipientType.TO));
            String cc = InternetAddressUtil.toString(jxMessage.getRecipients(RecipientType.CC));
            String bcc = InternetAddressUtil.toString(jxMessage.getRecipients(RecipientType.BCC));
            Date sentDate = jxMessage.getSentDate();
            String subject = jxMessage.getSubject();
            String flags = getFlags(jxMessage);
            long remoteMessageId = getUID(jxFolder, jxMessage);
            String contentType = jxMessage.getContentType();

            try {
                MessageLocalServiceUtil.getMessage(folderId, remoteMessageId);
            } catch (NoSuchMessageException nsme) {
                MessageLocalServiceUtil.addMessage(_user.getUserId(), folderId, sender, to, cc, bcc, sentDate,
                        subject, StringPool.BLANK, flags, remoteMessageId, contentType);
            }
        }

        com.liferay.mail.model.Folder folder = FolderLocalServiceUtil.getFolder(folderId);

        FolderLocalServiceUtil.updateFolder(folderId, folder.getFullName(), folder.getDisplayName(),
                jxFolder.getMessageCount());
    } catch (MessagingException me) {
        throw new MailException(me);
    }

    if (_log.isDebugEnabled()) {
        stopWatch.stop();

        _log.debug("Downloaded " + jxMessages.length + " messages from folder " + jxFolder.getFullName()
                + " completed in " + stopWatch.getTime() + " ms");
    }
}