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.mycompany.apsdtask.domain.MessageToEmailConverter.java

@Override
public EMail convert(Message message) {
    EMail eMail = new EMail();
    try {//from w ww . j  a  va2  s  .c om
        eMail.setAuthor(((InternetAddress) message.getFrom()[0]).getAddress());
        eMail.setDate(message.getSentDate());
        eMail.setSubject(message.getSubject());
        Object contnet = message.getContent();
        eMail.setBody((contnet instanceof MimeMultipart)
                ? ((MimeMultipart) contnet).getBodyPart(0).getContent().toString()
                : contnet.toString());
    } catch (IOException | MessagingException e) {
        throw new RuntimeException(e);
    }
    return eMail;
}

From source file:org.mule.transport.email.MailMuleMessageFactory.java

protected void addSentDateProperty(DefaultMuleMessage muleMessage, Message mailMessage)
        throws MessagingException {
    Date sentDate = mailMessage.getSentDate();
    if (sentDate == null) {
        sentDate = new Date();
    }/*from  w w  w.j  a  va2  s.  c  o  m*/
    muleMessage.setInboundProperty(MailProperties.SENT_DATE_PROPERTY, sentDate);
}

From source file:de.mmichaelis.maven.mojo.MailDevelopersMojoTest.java

@Test
public void testFullyConfiguredMail() throws Exception {
    final MavenProject project = mock(MavenProject.class);
    when(project.getDevelopers()).thenReturn(Arrays.asList(developers));
    mojoWrapper.setProject(project);//from  w  ww. j a  va2  s. com
    mojoWrapper.setCharset("UTF-8");
    mojoWrapper.setExpires("2");
    final String from = "John Doe <johndoe@github.com>";
    mojoWrapper.setFrom(from);
    mojoWrapper.setPriority("high");
    final String subject = "testFullyConfiguredMail";
    mojoWrapper.setSubject(subject);
    final String topic = "MyTopic";
    mojoWrapper.setTopic(topic);
    final Date now = new Date();
    mojoWrapper.execute();
    final Mailbox inbox = Mailbox.get(developers[0].getEmail());
    assertEquals("One new email for the first developer.", 1, inbox.size());
    final Message message = inbox.get(0);
    assertTrue("Sent date should signal to be today.", DateUtils.isSameDay(now, message.getSentDate()));
    assertEquals("Size of recipients should match number of developers.", developers.length,
            message.getAllRecipients().length);
    final Address[] senders = message.getFrom();
    assertNotNull("Sender address should be set.", senders);
    assertEquals("Number of senders should be 1.", 1, senders.length);
    assertEquals("Sender in message should match original sender.", from, senders[0].toString());
    final String messageSubject = message.getSubject();
    assertTrue("Subject should contain original subject.", messageSubject.contains(subject));
    assertTrue("Subject should contain topic.", messageSubject.contains(topic));

    // TODO: Check additional headers
}

From source file:FolderModel.java

protected String[] getCachedData(int row) {
    if (cached[row] == null) {
        try {/* w ww.  j a va 2s.co  m*/
            Message m = messages[row];

            String[] theData = new String[4];

            // Date
            Date date = m.getSentDate();
            if (date == null) {
                theData[0] = "Unknown";
            } else {
                theData[0] = date.toString();
            }

            // From
            Address[] adds = m.getFrom();
            if (adds != null && adds.length != 0) {
                theData[1] = adds[0].toString();
            } else {
                theData[1] = "";
            }

            // Subject
            String subject = m.getSubject();
            if (subject != null) {
                theData[2] = subject;
            } else {
                theData[2] = "(No Subject)";
            }

            cached[row] = theData;
        } catch (MessagingException e) {
            e.printStackTrace();
        }
    }

    return cached[row];
}

From source file:MainClass.java

public static void dumpEnvelope(Message m) throws Exception {
    pr("This is the message envelope");
    pr("---------------------------");
    Address[] a;/*from w w  w. ja  v a  2 s . c o  m*/
    // FROM
    if ((a = m.getFrom()) != null) {
        for (int j = 0; j < a.length; j++)
            pr("FROM: " + a[j].toString());
    }

    // TO
    if ((a = m.getRecipients(Message.RecipientType.TO)) != null) {
        for (int j = 0; j < a.length; j++) {
            pr("TO: " + a[j].toString());
            InternetAddress ia = (InternetAddress) a[j];
            if (ia.isGroup()) {
                InternetAddress[] aa = ia.getGroup(false);
                for (int k = 0; k < aa.length; k++)
                    pr("  GROUP: " + aa[k].toString());
            }
        }
    }

    // SUBJECT
    pr("SUBJECT: " + m.getSubject());

    // DATE
    Date d = m.getSentDate();
    pr("SendDate: " + (d != null ? d.toString() : "UNKNOWN"));

    // FLAGS
    Flags flags = m.getFlags();
    StringBuffer sb = new StringBuffer();
    Flags.Flag[] sf = flags.getSystemFlags(); // get the system flags

    boolean first = true;
    for (int i = 0; i < sf.length; i++) {
        String s;
        Flags.Flag f = sf[i];
        if (f == Flags.Flag.ANSWERED)
            s = "\\Answered";
        else if (f == Flags.Flag.DELETED)
            s = "\\Deleted";
        else if (f == Flags.Flag.DRAFT)
            s = "\\Draft";
        else if (f == Flags.Flag.FLAGGED)
            s = "\\Flagged";
        else if (f == Flags.Flag.RECENT)
            s = "\\Recent";
        else if (f == Flags.Flag.SEEN)
            s = "\\Seen";
        else
            continue; // skip it
        if (first)
            first = false;
        else
            sb.append(' ');
        sb.append(s);
    }

    String[] uf = flags.getUserFlags(); // get the user flag strings
    for (int i = 0; i < uf.length; i++) {
        if (first)
            first = false;
        else
            sb.append(' ');
        sb.append(uf[i]);
    }
    pr("FLAGS: " + sb.toString());

    // X-MAILER
    String[] hdrs = m.getHeader("X-Mailer");
    if (hdrs != null)
        pr("X-Mailer: " + hdrs[0]);
    else
        pr("X-Mailer NOT available");
}

From source file:com.cubusmail.server.services.ConvertUtil.java

/**
 * @param folder//from  ww  w.  j  a  va  2  s .c o  m
 * @param msg
 * @param result
 * @throws MessagingException
 */
private static void convertToStringArray(IMAPFolder folder, Message msg, GWTMessageRecord result,
        DateFormat dateFormat, NumberFormat decimalFormat) throws MessagingException {

    result.setId(Long.toString(folder.getUID(msg)));
    try {
        result.setAttachmentImage(MessageUtils.hasAttachments(msg) ? ImageProvider.MSG_ATTACHMENT : null);
    } catch (IOException e) {
        // do nothing
    }
    GWTMessageFlags flags = new GWTMessageFlags();
    flags.setDeleted(msg.isSet(Flags.Flag.DELETED));
    flags.setUnread(!msg.isSet(Flags.Flag.SEEN));
    flags.setAnswered(msg.isSet(Flags.Flag.ANSWERED));
    flags.setDraft(msg.isSet(Flags.Flag.DRAFT));
    result.setFlags(flags);

    result.setProrityImage(getPriorityImage(msg));
    result.setSubject(HtmlUtils.htmlEscape(msg.getSubject()));

    result.setFrom(
            HtmlUtils.htmlEscape(MessageUtils.getMailAdressString(msg.getFrom(), AddressStringType.PERSONAL)));
    result.setTo(HtmlUtils.htmlEscape(
            MessageUtils.getMailAdressString(msg.getRecipients(RecipientType.TO), AddressStringType.PERSONAL)));
    if (msg.getSentDate() != null) {
        result.setSendDateString(HtmlUtils.htmlEscape(dateFormat.format(msg.getSentDate())));
        result.setSendDate(msg.getSentDate());
    }

    int msgSize = MessageUtils.calculateAttachmentSize(msg.getSize());
    result.setSizeString(HtmlUtils.htmlEscape(MessageUtils.formatPartSize(msgSize, decimalFormat)));
    result.setSize(msgSize);
}

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

/**
 * Import messages//from  w ww .j  av  a  2s.  com
 * 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:msgshow.java

public static void dumpEnvelope(Message m) throws Exception {
    pr("This is the message envelope");
    pr("---------------------------");
    Address[] a;/*from   w  ww  .j  ava2  s. com*/
    // FROM 
    if ((a = m.getFrom()) != null) {
        for (int j = 0; j < a.length; j++)
            pr("FROM: " + a[j].toString());
    }

    // REPLY TO
    if ((a = m.getReplyTo()) != null) {
        for (int j = 0; j < a.length; j++)
            pr("REPLY TO: " + a[j].toString());
    }

    // TO
    if ((a = m.getRecipients(Message.RecipientType.TO)) != null) {
        for (int j = 0; j < a.length; j++) {
            pr("TO: " + a[j].toString());
            InternetAddress ia = (InternetAddress) a[j];
            if (ia.isGroup()) {
                InternetAddress[] aa = ia.getGroup(false);
                for (int k = 0; k < aa.length; k++)
                    pr("  GROUP: " + aa[k].toString());
            }
        }
    }

    // SUBJECT
    pr("SUBJECT: " + m.getSubject());

    // DATE
    Date d = m.getSentDate();
    pr("SendDate: " + (d != null ? d.toString() : "UNKNOWN"));

    // FLAGS
    Flags flags = m.getFlags();
    StringBuffer sb = new StringBuffer();
    Flags.Flag[] sf = flags.getSystemFlags(); // get the system flags

    boolean first = true;
    for (int i = 0; i < sf.length; i++) {
        String s;
        Flags.Flag f = sf[i];
        if (f == Flags.Flag.ANSWERED)
            s = "\\Answered";
        else if (f == Flags.Flag.DELETED)
            s = "\\Deleted";
        else if (f == Flags.Flag.DRAFT)
            s = "\\Draft";
        else if (f == Flags.Flag.FLAGGED)
            s = "\\Flagged";
        else if (f == Flags.Flag.RECENT)
            s = "\\Recent";
        else if (f == Flags.Flag.SEEN)
            s = "\\Seen";
        else
            continue; // skip it
        if (first)
            first = false;
        else
            sb.append(' ');
        sb.append(s);
    }

    String[] uf = flags.getUserFlags(); // get the user flag strings
    for (int i = 0; i < uf.length; i++) {
        if (first)
            first = false;
        else
            sb.append(' ');
        sb.append(uf[i]);
    }
    pr("FLAGS: " + sb.toString());

    // X-MAILER
    String[] hdrs = m.getHeader("X-Mailer");
    if (hdrs != null)
        pr("X-Mailer: " + hdrs[0]);
    else
        pr("X-Mailer NOT available");
}

From source file:com.jlgranda.fede.ejb.mail.reader.FacturaElectronicaMailReader.java

/**
 * Leer el inbox de <tt>Subject</tt>
 *
 * @param _subject la instancia <tt>Subject</tt> para la cual ingresar al
 * inbox y cargar las facturas//from w  ww .j  ava2 s. c om
 * @param folder
 * @return Lista de objetos <tt>FacturaReader</tt>
 * @throws javax.mail.MessagingException
 * @throws java.io.IOException
 */
public List<FacturaReader> read(Subject _subject, String folder) throws MessagingException, IOException {

    List<FacturaReader> result = new ArrayList<>();
    String server = settingService.findByName("mail.imap.host").getValue();
    //Todo definir una mejor forma de manejar la cuenta de correo
    String username = _subject.getFedeEmail();
    String password = _subject.getFedeEmailPassword();
    //String port = settingService.findByName("mail.imap.port").getValue();

    //String proto = "true".equalsIgnoreCase(settingService.findByName("mail.smtp.starttls.enable").getValue()) ? "TLS" : null;

    ///logger.info("Conectanto a servidor de correo # {}:\n\t Username: {}\n\t Password: {}\n\t ", server, username, password);
    IMAPClient client = new IMAPClient(server, username, password);

    Address[] fromAddress = null;
    String from = "";
    String subject = "";
    String sentDate = "";
    FacturaReader facturaReader = null;
    String[] token = null;
    List<String> urls = new ArrayList<>(); //Guardar enlaces a factura si es el caso
    boolean facturaEncontrada = false;
    Factura factura = null;
    EmailHelper emailHelper = new EmailHelper();
    MessageBuilder builder = new DefaultMessageBuilder();
    ByteArrayOutputStream os = null;
    for (Message message : client.getMessages(folder, false)) {
        //attachFiles = "";
        fromAddress = message.getFrom();
        from = fromAddress[0].toString();
        subject = message.getSubject();
        sentDate = message.getSentDate() != null ? message.getSentDate().toString() : "";

        facturaEncontrada = false;

        try {
            org.apache.james.mime4j.dom.Message mime4jMessage = builder
                    .parseMessage(new ByteArrayInputStream(emailHelper.fullMail(message).getBytes()));
            result.addAll(handleMessage(mime4jMessage));
        } catch (org.apache.james.mime4j.MimeIOException | org.apache.james.mime4j.MimeException ex) {
            logger.error("Fail to read message: " + subject, ex);
        } catch (Exception ex) {
            logger.error("Fail to read message with General Exception: " + subject, ex);
        }
    }

    client.close();

    logger.info("Readed {} email messages!", result.size());

    return result;
}

From source file:com.cubusmail.mail.util.MessageUtils.java

/**
 * Filter the messages./*from w  w  w  .  j ava  2s . c  o  m*/
 * 
 * @param msgs
 * @param searchFields
 * @param searchText
 * @return
 */
public static Message[] quickFilterMessages(Message[] msgs, String searchFields, String searchText) {

    if (!StringUtils.isEmpty(searchFields) && !StringUtils.isEmpty(searchText)) {
        searchFields = StringUtils.remove(searchFields, '[');
        searchFields = StringUtils.remove(searchFields, ']');
        searchFields = StringUtils.remove(searchFields, '\"');
        String[] fields = StringUtils.split(searchFields, ',');
        List<Message> filteredMsgs = new ArrayList<Message>();

        Date searchDate = null;
        try {
            searchDate = DateUtils.parseDate(searchText, new String[] { "dd.MM.yyyy" });
        } catch (Exception e) {
            // do nothing
        }

        try {
            for (Message message : msgs) {
                boolean contains = false;
                for (String searchField : fields) {
                    if (MessageListFields.SUBJECT.name().equals(searchField)) {
                        String subject = message.getSubject();
                        contains = StringUtils.containsIgnoreCase(subject, searchText);
                    } else if (MessageListFields.FROM.name().equals(searchField)) {
                        String from = MessageUtils.getMailAdressString(message.getFrom(),
                                AddressStringType.COMPLETE);
                        contains = StringUtils.containsIgnoreCase(from, searchText) || contains;
                    } else if (searchDate != null && MessageListFields.DATE.name().equals(searchField)) {
                        Date sendDate = message.getSentDate();
                        contains = (sendDate != null && DateUtils.isSameDay(searchDate, sendDate)) || contains;
                    }
                }
                if (contains) {
                    filteredMsgs.add(message);
                }
            }
        } catch (MessagingException ex) {
            log.warn(ex.getMessage(), ex);
        }

        return filteredMsgs.toArray(new Message[0]);
    }

    return msgs;
}