Example usage for javax.mail.internet MimeMessage getSentDate

List of usage examples for javax.mail.internet MimeMessage getSentDate

Introduction

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

Prototype

@Override
public Date getSentDate() throws MessagingException 

Source Link

Document

Returns the value of the RFC 822 "Date" field.

Usage

From source file:com.icegreen.greenmail.store.SimpleMessageAttributes.java

/**
 * Compute "sent" date// w w  w.  jav  a 2 s .com
 *
 * @param msg        Message to take sent date from. May be null to use default
 * @param defaultVal Default if sent date is not present
 * @return Sent date or now if no date could be found
 */
private static Date getSentDate(MimeMessage msg, Date defaultVal) {
    if (msg == null) {
        return defaultVal;
    }
    try {
        Date sentDate = msg.getSentDate();
        if (sentDate == null) {
            return defaultVal;
        } else {
            return sentDate;
        }
    } catch (MessagingException me) {
        return new Date();
    }
}

From source file:javamailclient.GmailAPI.java

public static Map getMessageDetails(String messageId) throws IOException, MessagingException {
    Map<String, String> mapDetails = new HashMap<String, String>();
    Message message = service.users().messages().get("me", messageId).setFormat("raw").execute();
    byte[] bytes = Base64.decodeBase64(message.getRaw());

    Properties prop = new Properties();
    Session session = Session.getDefaultInstance(prop, null);

    MimeMessage email = new MimeMessage(session, new ByteArrayInputStream(bytes));
    mapDetails.put("subject", email.getSubject());
    String from = "None";
    if (email.getSender() != null) {
        from = email.getSender().toString();
    }/*  w w  w.  j  av a2 s .com*/
    mapDetails.put("from", from);
    String date = "Unknown";
    if (email.getReceivedDate() != null) {
        date = email.getReceivedDate().toString();
    }
    mapDetails.put("receiveddate", date);
    date = "Unknown";
    if (email.getSentDate() != null) {
        date = email.getSentDate().toString();
    }
    mapDetails.put("senddate", date);
    mapDetails.put("body", getMessageBody(email));
    return mapDetails;
}

From source file:gmailclientfx.core.GmailClient.java

public static MyMessage fetchMessage(MimeMessage m, int tblIndex, String lbl) {
    MyMessage myMsg = null;/*from  w  w  w .  j  a  v a  2 s  .  co  m*/
    try {
        MimeMessage msg = new MimeMessage(m);
        MimeMessageParser parser = new MimeMessageParser(msg);
        parser.parse();

        String naslov = parser.getSubject();
        String from = parser.getFrom();
        List<Address> to = parser.getTo();//msg.getRecipients(javax.mail.Message.RecipientType.TO);
        String toStr = to.toString().replace("[", "").replace("]", "");
        if (toStr.equals(""))
            toStr = GmailClient.getEmail();
        String body = "";
        if (parser.hasHtmlContent())
            body = parser.getHtmlContent();
        else
            body = parser.getPlainContent();
        String date = msg.getSentDate().toString();
        String label = lbl;

        myMsg = new MyMessage(User.getUserId(GmailClient.getEmail()), naslov, from, toStr, body, date, label);
        myMsg.setTblId(tblIndex);
    } catch (MessagingException ex) {
        Logger.getLogger(GmailClient.class.getName()).log(Level.SEVERE, null, ex);
    } catch (Exception ex) {
        Logger.getLogger(GmailClient.class.getName()).log(Level.SEVERE, null, ex);
    }
    return myMsg;
}

From source file:com.joshlong.lazyblogger.integrations.EmailToBlogTransformer.java

public Message<?> transformFromMimeMessageToBlogPost(Message<?> msg) {
    Message<?> response = null; // if this is null, the message will just get dropped.
    BlogPost blogPost = new BlogPost();
    try {/*from ww  w.j a va  2  s  .  com*/

        MimeMessage mimeMessage = (MimeMessage) msg.getPayload();
        blogPost.setSubject(mimeMessage.getSubject());
        blogPost.setDate(mimeMessage.getSentDate());
        blogPost.setBody(IOUtils.toString(mimeMessage.getInputStream()));

        if (mimeMessage.getSender() != null)
            blogPost.addSender(emailFromAddress(mimeMessage.getSender()));

        if (mimeMessage.getFrom() != null)
            for (Address address : mimeMessage.getFrom())
                blogPost.addSender(emailFromAddress(address));

        response = MessageBuilder.withPayload(blogPost).copyHeadersIfAbsent(msg.getHeaders()).build();
    } catch (Throwable e) {
        utilities.log(ExceptionUtils.getFullStackTrace(e));
    }
    return response;
}

From source file:org.ofbiz.common.CommonServices.java

public static Map<String, Object> mcaTest(DispatchContext dctx, Map<String, ?> context) {
    MimeMessageWrapper wrapper = (MimeMessageWrapper) context.get("messageWrapper");
    MimeMessage message = wrapper.getMessage();
    try {//from   w  w w.  j  a  va2  s  .  co m
        if (message.getAllRecipients() != null) {
            Debug.log("To: " + UtilMisc.toListArray(message.getAllRecipients()), module);
        }
        if (message.getFrom() != null) {
            Debug.log("From: " + UtilMisc.toListArray(message.getFrom()), module);
        }
        Debug.log("Subject: " + message.getSubject(), module);
        if (message.getSentDate() != null) {
            Debug.log("Sent: " + message.getSentDate().toString(), module);
        }
        if (message.getReceivedDate() != null) {
            Debug.log("Received: " + message.getReceivedDate().toString(), module);
        }
    } catch (Exception e) {
        Debug.logError(e, module);
    }
    return ServiceUtil.returnSuccess();
}

From source file:com.silverpeas.mailinglist.service.job.MailProcessor.java

/**
 * Process an email, extracting attachments and constructing a Message.
 *
 * @param mail the email to be processed.
 * @param mailingList the mailing list it is going to be affected to.
 * @param event the event which will be send at the end of all processing.
 * @throws MessagingException/*from ww  w .j a  v a2  s  . com*/
 * @throws IOException
 */
public void prepareMessage(MimeMessage mail, MessageListener mailingList, MessageEvent event)
        throws MessagingException, IOException {
    String sender = ((InternetAddress[]) mail.getFrom())[0].getAddress();
    if (!mailingList.checkSender(sender)) {
        return;
    }
    Message message = new Message();
    message.setComponentId(mailingList.getComponentId());
    message.setSender(sender);
    message.setSentDate(mail.getSentDate());
    message.setMessageId(mail.getMessageID());
    String[] referenceId = mail.getHeader(MAIL_HEADER_IN_REPLY_TO);
    if (referenceId == null || referenceId.length == 0) {
        referenceId = mail.getHeader(MAIL_HEADER_REFERENCES);
    }
    if (referenceId == null || referenceId.length == 0) {
        message.setReferenceId(null);
    } else {
        message.setReferenceId(referenceId[0]);
    }
    message.setTitle(mail.getSubject());
    SilverTrace.info("mailingList", "MailProcessor.prepareMessage()", "mailinglist.notification.error",
            "Processing message " + mail.getSubject());
    Object content = mail.getContent();
    if (content instanceof Multipart) {
        processMultipart((Multipart) content, message);
    } else if (content instanceof String) {
        processBody((String) content, mail.getContentType(), message);
    }
    event.addMessage(message);
}

From source file:gmailclientfx.models.FetchMessageCallable.java

public MyMessage fetchMessage(MimeMessage m, int tblIndex, String lbl) throws MessagingException, Exception {
    MimeMessage msg = new MimeMessage(m);
    MimeMessageParser parser = new MimeMessageParser(msg);
    parser.parse();/*  w  w w  .java2s.  c o  m*/

    String naslov = parser.getSubject();
    String from = parser.getFrom();
    Address[] to = msg.getRecipients(Message.RecipientType.TO);
    String toStr = "";
    if (to.length > 1) {
        for (int k = 0; k < to.length; k++) {
            if (k == to.length - 1)
                toStr += to[k].toString();
            else
                toStr += to[k].toString() + ",";
        }
    } else {
        toStr = to[0].toString();
    }
    String body = parser.getHtmlContent();
    if (body.equals(""))
        body = parser.getPlainContent();
    String date = msg.getSentDate().toString();
    String label = lbl;

    MyMessage myMsg = new MyMessage(User.getUserId(GmailClient.getEmail()), naslov, from, toStr, body, date,
            label);
    myMsg.setTblId(tblIndex);
    return myMsg;
}

From source file:ca.airspeed.demo.testingemail.EmailServiceTest.java

/**
 * When we send out an email with just a text body, et expect to get a
 * Multipart email having only a plain text body.
 *//*from  w w w.  j a va  2  s . c o  m*/
@Test
public void testSimpleEmail() throws Exception {
    // Given:
    EmailService service = makeALocalMailer();

    InternetAddress expectedTo = new InternetAddress("Indiana.Jones@domain.com", "Indiana Jones");
    String expectedSubject = "This is a Test Email";
    String expectedTextBody = "This is a simple test.";

    // When:
    service.sendSimpleEmail(expectedTo, expectedSubject, expectedTextBody);

    // Then:
    List<WiserMessage> messages = wiser.getMessages();
    assertEquals("Number of messages sent;", 1, messages.size());

    WiserMessage message = messages.get(0);
    assertNotNull("No message was actually sent.", message);
    MimeMessage mimeMessage = message.getMimeMessage();
    Address[] toRecipients = mimeMessage.getRecipients(RecipientType.TO);
    assertEquals("Number of To: Recipient;", 1, toRecipients.length);
    Address toRecipient = toRecipients[0];
    assertEquals("To: Recipient;", expectedTo, toRecipient);

    InternetAddress expectedFrom = new InternetAddress("admin@domain.com", "Domain Admin");
    Address[] fromArr = mimeMessage.getFrom();
    assertEquals("From: email addresses;", 1, fromArr.length);
    assertEquals("Email From: address,", expectedFrom, fromArr[0]);

    assertEquals("Subject;", expectedSubject, mimeMessage.getSubject());

    assertNotNull("The date of the email cannot be null.", mimeMessage.getSentDate());

    MimeMultipart body = ((MimeMultipart) mimeMessage.getContent());
    assertEquals("Number of MIME Parts in the body;", 1, body.getCount());
    MimeMultipart textPart = ((MimeMultipart) body.getBodyPart(0).getContent());
    assertEquals("Number of MIME parts in the text body;", 1, textPart.getCount());
    MimeBodyPart plainTextPart = ((MimeBodyPart) textPart.getBodyPart(0));
    assertTrue("Expected the plain text content to be text/plain.", plainTextPart.isMimeType("text/plain"));
    assertEquals("Text Body;", expectedTextBody, plainTextPart.getContent());
}

From source file:com.silverpeas.mailinglist.service.job.TestMessageChecker.java

@Test
public void testProcessEmailHtmlText() throws MessagingException, IOException {
    MessageListener mockListener1 = mock(MessageListener.class);
    when(mockListener1.getComponentId()).thenReturn("componentId");
    when(mockListener1.checkSender("bart.simpson@silverpeas.com")).thenReturn(Boolean.TRUE);
    MessageListener mockListener2 = mock(MessageListener.class);
    Map<String, MessageListener> listenersByEmail = new HashMap<String, MessageListener>(2);
    listenersByEmail.put("thesimpsons@silverpeas.com", mockListener1);
    listenersByEmail.put("theflanders@silverpeas.com", mockListener2);
    MimeMessage mail = new MimeMessage(messageChecker.getMailSession());
    InternetAddress bart = new InternetAddress("bart.simpson@silverpeas.com");
    InternetAddress theSimpsons = new InternetAddress("thesimpsons@silverpeas.com");
    mail.addFrom(new InternetAddress[] { bart });
    mail.addRecipient(RecipientType.TO, theSimpsons);
    mail.setSubject("Simple html Email test");
    String html = loadHtml();/*  w  w w.j  a  va  2s.  c  o  m*/
    mail.setText(html, "UTF-8", "html");
    mail.setSentDate(new Date());
    Date sentDate = new Date(mail.getSentDate().getTime());
    Transport.send(mail);
    Map<MessageListener, MessageEvent> events = new HashMap<MessageListener, MessageEvent>();
    messageChecker.processEmail(mail, events, listenersByEmail);
    assertNotNull(events);
    assertEquals(1, events.size());
    assertNull(events.get(mockListener2));

    MessageEvent event = events.get(mockListener1);
    assertNotNull(event);
    assertNotNull(event.getMessages());
    assertEquals(1, event.getMessages().size());
    Message message = event.getMessages().get(0);
    assertEquals("bart.simpson@silverpeas.com", message.getSender());
    assertEquals("Simple html Email test", message.getTitle());
    assertEquals(html, message.getBody());
    assertNotNull(message.getSentDate());
    assertEquals(sentDate.getTime(), message.getSentDate().getTime());
    assertEquals(htmlEmailSummary, message.getSummary());
    assertEquals(0, message.getAttachmentsSize());
    assertEquals(0, message.getAttachments().size());
    assertEquals("componentId", message.getComponentId());
    assertEquals("text/html; charset=UTF-8", message.getContentType());
    verify(mockListener1, atLeastOnce()).checkSender("bart.simpson@silverpeas.com");
}

From source file:com.opensearchserver.extractor.parser.Eml.java

@Override
protected void parseContent(InputStream inputStream, String extension, String mimeType) throws Exception {
    Session session = Session.getDefaultInstance(JAVAMAIL_PROPS);

    MimeMessage mimeMessage = new MimeMessage(session, inputStream);
    MimeMessageParser mimeMessageParser = new MimeMessageParser(mimeMessage).parse();

    ParserDocument document = getNewParserDocument();
    String from = mimeMessageParser.getFrom();
    if (from != null)
        document.add(FROM, from.toString());
    for (Address address : mimeMessageParser.getTo())
        document.add(RECIPIENT_TO, address.toString());
    for (Address address : mimeMessageParser.getCc())
        document.add(RECIPIENT_CC, address.toString());
    for (Address address : mimeMessageParser.getBcc())
        document.add(RECIPIENT_BCC, address.toString());
    document.add(SUBJECT, mimeMessageParser.getSubject());
    document.add(HTML_CONTENT, mimeMessageParser.getHtmlContent());
    document.add(PLAIN_CONTENT, mimeMessageParser.getPlainContent());
    document.add(SENT_DATE, mimeMessage.getSentDate());
    document.add(RECEIVED_DATE, mimeMessage.getReceivedDate());

    for (DataSource dataSource : mimeMessageParser.getAttachmentList()) {
        document.add(ATTACHMENT_NAME, dataSource.getName());
        document.add(ATTACHMENT_TYPE, dataSource.getContentType());
        // TODO Extract content from attachmend
        // if (parserSelector != null) {
        // Parser attachParser = parserSelector.parseStream(
        // getSourceDocument(), dataSource.getName(),
        // dataSource.getContentType(), null,
        // dataSource.getInputStream(), null, null, null);
        // if (attachParser != null) {
        // List<ParserResultItem> parserResults = attachParser
        // .getParserResults();
        // if (parserResults != null)
        // for (ParserResultItem parserResult : parserResults)
        // result.addField(
        // ParserFieldEnum.email_attachment_content,
        // parserResult);
        // }/*from ww w .ja v  a 2 s.co m*/
        // }
    }
    if (StringUtils.isEmpty(mimeMessageParser.getHtmlContent()))
        document.add(LANG_DETECTION, languageDetection(document, PLAIN_CONTENT, 10000));
    else
        document.add(LANG_DETECTION, languageDetection(document, HTML_CONTENT, 10000));
}