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:server.MailPop3Expert.java

@Override
public void run() {
    //obtengo la agenda
    List<String> agenda = XmlParcerExpert.getInstance().getAgenda();

    while (store.isConnected()) {
        try {//from   w  ww  .ja v  a  2  s .c o  m

            // Abre la carpeta INBOX
            Folder folderInbox = store.getFolder("INBOX");
            folderInbox.open(Folder.READ_ONLY);

            // Obtiene los mails
            Message[] arrayMessages = folderInbox.getMessages();

            //procesa los mails
            for (int i = 0; i < arrayMessages.length; i++) {
                Message message = arrayMessages[i];
                Address[] fromAddress = message.getFrom();
                String from = fromAddress[0].toString();
                String subject = message.getSubject();
                String sentDate = message.getSentDate().toString();
                String messageContent = "";
                String contentType = message.getContentType();

                if (contentType.contains("multipart")) {
                    // Si el contenido es mulpart
                    Multipart multiPart = (Multipart) message.getContent();
                    int numberOfParts = multiPart.getCount();
                    for (int partCount = 0; partCount < numberOfParts; partCount++) {
                        MimeBodyPart part = (MimeBodyPart) multiPart.getBodyPart(partCount);
                        if (Part.ATTACHMENT.equalsIgnoreCase(part.getDisposition())) {
                            // si contiene un archivo
                        } else {
                            // el contenido del mensaje
                            messageContent = part.getContent().toString();
                        }
                    }

                } else if (contentType.contains("text/plain") || contentType.contains("text/html")) {
                    Object content = message.getContent();
                    if (content != null) {
                        messageContent = content.toString();
                    }
                }

                //parseo del from
                if (from.contains("<")) {
                    from = from.substring(from.indexOf("<") + 1, from.length() - 1);
                }

                //si esta en la agenda
                if (agenda.contains(from)) {
                    //obtiene la trama
                    try {
                        messageContent = messageContent.substring(messageContent.indexOf("&gt"),
                                messageContent.indexOf("&lt;") + 4);
                        if (messageContent.startsWith("&gt") && messageContent.endsWith("&lt;")) {
                            //procesa el mail
                            XmlParcerExpert.getInstance().processAndSaveMail(from, messageContent);
                            frame.loadMails();
                        }
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                } else {
                    //no lo guarda
                }

            }

            folderInbox.close(false);

            //duerme el hilo por el tiempo de la frecuencia
            Thread.sleep(frecuency * 60 * 1000);

        } catch (IOException e) {
            e.printStackTrace();
        } catch (InterruptedException ex) {
            //Logger.getLogger(MailPop3Expert.class.getName()).log(Level.SEVERE, null, ex);
        } catch (MessagingException ex) {
            //Logger.getLogger(MailPop3Expert.class.getName()).log(Level.SEVERE, null, ex);
        }
    }

}

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

/**
 * Convert Mime Message to Mail/*  w ww .j  av  a2s . 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:com.openkm.util.MailUtils.java

/**
 * Import messages//from  w ww.j av  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);
            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:com.openkm.util.MailUtils.java

/**
 * Convert Mime Message to Mail//from w w w  . j a  v  a 2 s.c  o  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.cubusmail.gwtui.server.services.ConvertUtil.java

/**
 * @param folder//from  www  .  j  a  va2s  .com
 * @param msg
 * @param result
 * @throws MessagingException
 */
public static void convertToStringArray(IMailFolder folder, Message msg, String[] result, DateFormat dateFormat,
        NumberFormat decimalFormat) throws MessagingException {

    result[MessageListFields.ID.ordinal()] = Long.toString(folder.getUID(msg));
    try {
        result[MessageListFields.ATTACHMENT_FLAG.ordinal()] = Boolean
                .toString(MessageUtils.hasAttachments(msg));
    } catch (IOException e) {
        // do nothing
    }
    result[MessageListFields.READ_FLAG.ordinal()] = Boolean.toString(msg.isSet(Flags.Flag.SEEN));
    result[MessageListFields.DELETED_FLAG.ordinal()] = Boolean.toString(msg.isSet(Flags.Flag.DELETED));
    result[MessageListFields.ANSWERED_FLAG.ordinal()] = Boolean.toString(msg.isSet(Flags.Flag.ANSWERED));
    result[MessageListFields.DRAFT_FLAG.ordinal()] = Boolean.toString(msg.isSet(Flags.Flag.DRAFT));
    result[MessageListFields.PRIORITY.ordinal()] = Integer.toString(MessageUtils.getMessagePriority(msg));
    if (!StringUtils.isEmpty(msg.getSubject())) {
        result[MessageListFields.SUBJECT.ordinal()] = msg.getSubject();
    }
    result[MessageListFields.FROM.ordinal()] = MessageUtils.getMailAdressString(msg.getFrom(),
            AddressStringType.PERSONAL);
    result[MessageListFields.TO.ordinal()] = MessageUtils
            .getMailAdressString(msg.getRecipients(RecipientType.TO), AddressStringType.PERSONAL);
    if (msg.getSentDate() != null) {
        result[MessageListFields.DATE.ordinal()] = dateFormat.format(msg.getSentDate());
    }
    result[MessageListFields.SIZE.ordinal()] = MessageUtils
            .formatPartSize(MessageUtils.calculateAttachmentSize(msg.getSize()), decimalFormat);
}

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

public void downloadEmails(String mailStoreProtocol, String mailStoreHost, String mailStoreUserName,
        String mailStorePassword) throws IOException {

    Session session = getMailStoreSession(mailStoreProtocol, mailStoreHost, mailStoreUserName,
            mailStorePassword);/*from w  w  w  . j av a 2  s  .c  o m*/
    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_ONLY);

        // 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 from = fromAddress[0].toString();
            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();
                }
            }

            // 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 Message: " + messageContent);
        }

        // disconnect
        folderInbox.close(false);
        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:de.kp.ames.web.function.access.imap.ImapConsumer.java

/**
 * @param m/*  w  w  w.  ja  v  a  2  s  .c  o  m*/
 * @return
 * @throws Exception
 */
private String mail2HTML(Message m) throws Exception {

    /*
     * Date & subject
     */
    String date = m.getSentDate().toString();
    String subject = m.getSubject();

    /*
     * Body
     */
    String body = getBody(m);

    /*
     * From
     */
    String from = "";

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

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

    }

    return HtmlRenderer.mail2HTML(from, date, subject, body);

}

From source file:nl.ordina.bag.etl.mail.handler.MessageHandler.java

public void handle(Message message)
        throws FileNotFoundException, IOException, MessagingException, JAXBException {
    if (message.getFrom()[0].toString().matches(fromAddressRegEx)
            && message.getSubject().matches(subjectRegEx)) {
        String content = IOUtils.toString(message.getInputStream());
        String url = getURL(content);
        if (url != null) {
            File mutatiesFile = httpClient.downloadFile(url);
            mutatiesFileLoader.execute(mutatiesFile);
            //mutatiesFile.delete();
        } else/*from w  w  w  . j av a  2  s .c o  m*/
            logger.warn("Could not retreive url from message '" + message.getSubject() + "' ["
                    + message.getSentDate() + "]");
    } else
        logger.debug("Skipping message '" + message.getSubject() + "' [" + message.getSentDate() + "]");
}

From source file:com.intranet.intr.inbox.EmpControllerInbox.java

public correoNoLeidos ltaRecibidos2(String name, int num) {
    correoNoLeidos lta = new correoNoLeidos();
    Properties props = System.getProperties();
    props.setProperty("mail.store.protocol", "imaps");
    try {//  w  ww .  j  a v  a2  s.  c om
        users u = usuarioService.getByLogin(name);
        Session session = Session.getDefaultInstance(props, null);
        Store store = session.getStore("imaps");

        store.connect("imap.1and1.es", u.getCorreoUsuario(), u.getCorreoContreasenna());

        System.out.println("ola" + store);

        Folder inbox = store.getFolder("Inbox");
        inbox.open(Folder.READ_ONLY);
        Calendar fecha3 = Calendar.getInstance();
        fecha3.roll(Calendar.MONTH, false);
        Message msg[] = inbox.search(new ReceivedDateTerm(ComparisonTerm.GT, fecha3.getTime()));
        //Message msg[] = inbox.getMessages();
        System.out.println("MAILS: " + msg.length);
        for (Message message : msg) {
            try {
                if (num == message.getMessageNumber()) {
                    //message.setFlag(Flags.Flag.SEEN, true);
                    lta.setNum(message.getMessageNumber());
                    lta.setFecha(message.getSentDate().toString());
                    lta.setDe(message.getFrom()[0].toString());
                    lta.setAsunto(message.getSubject().toString());
                    correoNoLeidos co = new correoNoLeidos();
                    List<String> arc = new ArrayList<String>();
                    List<String> rar = new ArrayList<String>();
                    correoNoLeidos cc = analizaParteDeMensaje2(co, arc, rar, message);
                    lta.setImagenes(cc.getImagenes());
                    lta.setRar(cc.getRar());
                    lta.setContenido(cc.getContenido());
                    String cont = "";

                    String contenido = "";

                    //lta.setContenido(analizaParteDeMensaje2(message));
                }
            } catch (Exception e) {
                System.out.println("No Information");
            }

        }
    } catch (MessagingException e) {
        System.out.println(e.toString());
    }

    return lta;
}

From source file:org.apache.jmeter.protocol.mail.sampler.MailReaderSampler.java

private void appendMessageData(SampleResult child, Message message) throws MessagingException, IOException {
    StringBuilder cdata = new StringBuilder();
    cdata.append("Date: "); // $NON-NLS-1$
    cdata.append(message.getSentDate());// TODO - use a different format here?
    cdata.append(NEW_LINE);/*from w ww. j  ava  2  s.  com*/

    cdata.append("To: "); // $NON-NLS-1$
    Address[] recips = message.getAllRecipients(); // may be null
    for (int j = 0; recips != null && j < recips.length; j++) {
        cdata.append(recips[j].toString());
        if (j < recips.length - 1) {
            cdata.append("; "); // $NON-NLS-1$
        }
    }
    cdata.append(NEW_LINE);

    cdata.append("From: "); // $NON-NLS-1$
    Address[] from = message.getFrom(); // may be null
    for (int j = 0; from != null && j < from.length; j++) {
        cdata.append(from[j].toString());
        if (j < from.length - 1) {
            cdata.append("; "); // $NON-NLS-1$
        }
    }
    cdata.append(NEW_LINE);

    cdata.append("Subject: "); // $NON-NLS-1$
    cdata.append(message.getSubject());
    cdata.append(NEW_LINE);

    cdata.append(NEW_LINE);
    Object content = message.getContent();
    if (content instanceof MimeMultipart) {
        appendMultiPart(child, cdata, (MimeMultipart) content);
    } else if (content instanceof InputStream) {
        child.setResponseData(IOUtils.toByteArray((InputStream) content));
    } else {
        cdata.append(content);
        child.setResponseData(cdata.toString(), child.getDataEncodingNoDefault());
    }
}