Example usage for javax.mail Message getFrom

List of usage examples for javax.mail Message getFrom

Introduction

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

Prototype

public abstract Address[] getFrom() throws MessagingException;

Source Link

Document

Returns the "From" attribute.

Usage

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 ww  .j a  va 2s .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.cubusmail.mail.util.MessageUtils.java

/**
 * Filter the messages.//w  ww . j  a va 2  s  . 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;
}

From source file:com.canoo.webtest.plugins.emailtest.AbstractSelectStep.java

boolean messageMatches(final Message message) throws MessagingException {
    if (!doMatch(getFrom(), message.getFrom()[0].toString())) {
        return false;
    }//from   www  .j  a  v a 2 s .  c  om
    if (!doMatch(getSubject(), message.getSubject())) {
        return false;
    }
    if (!doMatchMultiple(getReplyTo(), message.getReplyTo())) {
        return false;
    }
    if (!doMatchMultiple(getCc(), message.getRecipients(MimeMessage.RecipientType.CC))) {
        return false;
    }
    return doMatchMultiple(getTo(), message.getRecipients(MimeMessage.RecipientType.TO));
}

From source file:org.springframework.integration.mail.transformer.AbstractMailMessageTransformer.java

private Map<String, Object> extractHeaderMapFromMailMessage(javax.mail.Message mailMessage) {
    try {//from  ww  w .ja v a  2 s .  c o  m
        Map<String, Object> headers = new HashMap<String, Object>();
        headers.put(MailHeaders.FROM, this.convertToString(mailMessage.getFrom()));
        headers.put(MailHeaders.BCC, this.convertToStringArray(mailMessage.getRecipients(RecipientType.BCC)));
        headers.put(MailHeaders.CC, this.convertToStringArray(mailMessage.getRecipients(RecipientType.CC)));
        headers.put(MailHeaders.TO, this.convertToStringArray(mailMessage.getRecipients(RecipientType.TO)));
        headers.put(MailHeaders.REPLY_TO, this.convertToString(mailMessage.getReplyTo()));
        headers.put(MailHeaders.SUBJECT, mailMessage.getSubject());
        return headers;
    } catch (Exception e) {
        throw new MessagingException("conversion of MailMessage headers failed", e);
    }
}

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

/**
 * Import messages/*w  w w  .ja  va2s  .  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:org.b3log.solo.mail.local.MailSender.java

/**
 * Converts the specified message into a {@link javax.mail.Message
 * javax.mail.Message}.//from   w  w  w  . j a v a 2s .  c o  m
 *
 * @param message the specified message
 * @return a {@link javax.mail.internet.MimeMessage}
 * @throws Exception if converts error
 */
public javax.mail.Message convert2JavaMailMsg(final Message message) throws Exception {
    if (null == message) {
        return null;
    }

    if (StringUtils.isBlank(message.getFrom())) {
        throw new MessagingException("Null from");
    }

    if (null == message.getRecipients() || message.getRecipients().isEmpty()) {
        throw new MessagingException("Null recipients");
    }

    final MimeMessage ret = new MimeMessage(getSession());

    ret.setFrom(new InternetAddress(message.getFrom()));
    final String subject = message.getSubject();

    ret.setSubject(MimeUtility.encodeText(subject != null ? subject : "", "UTF-8", "B"));
    final String htmlBody = message.getHtmlBody();

    ret.setContent(htmlBody != null ? htmlBody : "", "text/html;charset=UTF-8");
    ret.addRecipients(RecipientType.TO, transformRecipients(message.getRecipients()));

    return ret;
}

From source file:gov.nih.nci.firebird.service.messages.email.EmailServiceImplTest.java

@Test
public void testSendMessage() throws MessagingException, IOException {
    bean.sendMessage(TEST_TO_ADDRESS, TEST_CC_ADDRESSES, TEST_BOUNCE_ADDRESS, testMessage);
    Message message = mailbox.get(0);
    InternetAddress fromAddress = (InternetAddress) message.getFrom()[0];
    assertEquals(TEST_FROM_ADDRESS, fromAddress.getAddress());
    assertEquals(TEST_FROM_NAME, fromAddress.getPersonal());
    InternetAddress toAddress = (InternetAddress) message.getRecipients(RecipientType.TO)[0];
    assertEquals(TEST_TO_ADDRESS, toAddress.getAddress());
    assertEquals(2, message.getRecipients(RecipientType.CC).length);
    InternetAddress ccAddress1 = (InternetAddress) message.getRecipients(RecipientType.CC)[0];
    InternetAddress ccAddress2 = (InternetAddress) message.getRecipients(RecipientType.CC)[1];
    assertEquals(TEST_CC_ADDRESSES.get(0), ccAddress1.getAddress());
    assertEquals(TEST_CC_ADDRESSES.get(1), ccAddress2.getAddress());
    assertEquals(TEST_SUBJECT, message.getSubject());
    assertEquals(TEST_CONTENT, message.getContent());
}

From source file:gov.nih.nci.firebird.service.messages.email.EmailServiceImplTest.java

private String doSendMessageTest(List<String> cc) throws MessagingException, IOException {
    String overrideEmail = "overrideEmail@example.com";
    mailbox = Mailbox.get(overrideEmail);
    bean.setOverrideEmailAddress(overrideEmail);
    bean.sendMessage(TEST_TO_ADDRESS, cc, null, testMessage);
    Message message = mailbox.get(0);
    InternetAddress fromAddress = (InternetAddress) message.getFrom()[0];
    assertEquals(TEST_FROM_ADDRESS, fromAddress.getAddress());
    assertEquals(TEST_FROM_NAME, fromAddress.getPersonal());
    InternetAddress toAddress = (InternetAddress) message.getRecipients(RecipientType.TO)[0];
    assertEquals(overrideEmail, toAddress.getAddress());
    assertNull(message.getRecipients(RecipientType.CC));
    assertEquals(TEST_SUBJECT, message.getSubject());
    assertTrue(message.getContent().toString().contains(TEST_CONTENT));
    assertTrue(message.getContent().toString().contains(EmailServiceImpl.TO_OVERRIDE_HEADING));
    assertTrue(message.getContent().toString().contains(TEST_TO_ADDRESS));
    assertTrue(message.getContent().toString().contains(EmailServiceImpl.LINE_SEPARATOR));

    return message.getContent().toString();
}

From source file:password.pwm.util.queue.EmailQueueManagerTest.java

@Test
public void testConvertEmailItemToMessage() throws MessagingException, IOException {
    EmailQueueManager emailQueueManager = new EmailQueueManager();

    Configuration config = Mockito.mock(Configuration.class);
    Mockito.when(config.readAppProperty(AppProperty.SMTP_SUBJECT_ENCODING_CHARSET)).thenReturn("UTF8");

    EmailItemBean emailItemBean = new EmailItemBean("fred@flintstones.tv, barney@flintstones.tv",
            "bedrock-admin@flintstones.tv", "Test Subject", "bodyPlain", "bodyHtml");

    List<Message> messages = emailQueueManager.convertEmailItemToMessages(emailItemBean, config);
    Assert.assertEquals(2, messages.size());

    Message message = messages.get(0);
    Assert.assertEquals(new InternetAddress("fred@flintstones.tv"),
            message.getRecipients(Message.RecipientType.TO)[0]);
    Assert.assertEquals(new InternetAddress("bedrock-admin@flintstones.tv"), message.getFrom()[0]);
    Assert.assertEquals("Test Subject", message.getSubject());
    String content = IOUtils.toString(message.getInputStream());
    Assert.assertTrue(content.contains("bodyPlain"));
    Assert.assertTrue(content.contains("bodyHtml"));

    message = messages.get(1);//from w ww. ja  v a 2  s .c om
    Assert.assertEquals(new InternetAddress("barney@flintstones.tv"),
            message.getRecipients(Message.RecipientType.TO)[0]);
    Assert.assertEquals(new InternetAddress("bedrock-admin@flintstones.tv"), message.getFrom()[0]);
    Assert.assertEquals("Test Subject", message.getSubject());
    content = IOUtils.toString(message.getInputStream());
    Assert.assertTrue(content.contains("bodyPlain"));
    Assert.assertTrue(content.contains("bodyHtml"));
}

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

protected void addFromProperty(DefaultMuleMessage muleMessage, Message mailMessage) {
    try {/*from  w w  w  . j  av a 2  s  .  co  m*/
        muleMessage.setInboundProperty(MailProperties.FROM_ADDRESS_PROPERTY,
                MailUtils.mailAddressesToString(mailMessage.getFrom()));
    } catch (javax.mail.MessagingException me) {
        log.warn("Invalid address found in From header:", me);
    }
}