Example usage for javax.mail Message getContent

List of usage examples for javax.mail Message getContent

Introduction

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

Prototype

public Object getContent() throws IOException, MessagingException;

Source Link

Document

Return the content as a Java object.

Usage

From source file:com.app.test.mail.DefaultMailSenderTest.java

@Test
public void testPopulateAccountDeletionMessage() throws Exception {
    _initializeVelocityTemplate(_clazz, _classInstance);

    Method populateMessage = _clazz.getDeclaredMethod("_populateMessage", String.class, String.class,
            String.class, Session.class);

    populateMessage.setAccessible(true);

    Message message = (Message) populateMessage.invoke(_classInstance, "user@test.com",
            "Account Deletion Successful", "account_deletion_email.vm", _session);

    Assert.assertEquals("Auction Alert <test@test.com>", message.getFrom()[0].toString());
    Assert.assertEquals("Account Deletion Successful", message.getSubject());
    Assert.assertEquals(_ACCOUNT_DELETION_EMAIL, message.getContent());

    InternetAddress[] internetAddresses = new InternetAddress[1];

    internetAddresses[0] = new InternetAddress("user@test.com");

    Assert.assertArrayEquals(internetAddresses, message.getRecipients(Message.RecipientType.TO));
}

From source file:org.campware.cream.modules.scheduledjobs.Pop3Job.java

private void doReceiveMessages() throws Exception {

    log.debug("Checking mail ");

    String host = Turbine.getConfiguration().getString("mail.pop3.host");
    String username = Turbine.getConfiguration().getString("mail.pop3.user");
    String password = Turbine.getConfiguration().getString("mail.pop3.password");

    // Create empty properties
    Properties props = new Properties();

    // Get session
    Session session = Session.getDefaultInstance(props, null);

    // Get the store
    Store store = session.getStore("pop3");

    // Connect to store
    store.connect(host, username, password);

    // Get folder
    Folder folder = store.getFolder("INBOX");

    // Open read-only
    folder.open(Folder.READ_WRITE);//from   w w  w. ja v  a  2s . c  o  m

    // Get attributes & flags for all messages
    //
    Message[] messages = folder.getMessages();
    FetchProfile fp = new FetchProfile();
    fp.add(FetchProfile.Item.ENVELOPE);
    fp.add(FetchProfile.Item.FLAGS);
    fp.add("X-Mailer");
    folder.fetch(messages, fp);

    for (int i = 0; i < messages.length; i++) {

        log.debug("Retrieving message " + i);

        // Process each message
        //
        InboxEvent entry = new InboxEvent();
        Address fromAddress = new InternetAddress();
        String from = new String();
        String name = new String();
        String email = new String();
        String replyTo = new String();
        String subject = new String();
        String content = new String();
        Date sentDate = new Date();
        int emailformat = 10;

        Message m = messages[i];

        // and now, handle the content
        Object o = m.getContent();

        // find content type
        if (m.isMimeType("text/plain")) {
            content = "<PRE style=\"font-size: 12px;\">" + (String) o + "</PRE>";
            emailformat = 10;
        } else if (m.isMimeType("text/html")) {
            content = (String) o;
            emailformat = 20;
        } else if (m.isMimeType("text/*")) {
            content = (String) o;
            emailformat = 30;
        } else if (m.isMimeType("multipart/alternative")) {
            try {
                content = handleAlternative(o, content);
                emailformat = 20;
            } catch (Exception ex) {
                content = "Problem with the message format. Messssage has left on the email server.";
                emailformat = 50;
                log.error(ex.getMessage(), ex);
            }
        } else if (m.isMimeType("multipart/*")) {
            try {
                content = handleMulitipart(o, content, entry);
                emailformat = 40;
            } catch (Exception ex) {
                content = "Problem with the message format. Messssage has left on the email server.";
                emailformat = 50;
                log.error(ex.getMessage(), ex);
            }
        } else {
            content = "Problem with the message format. Messssage has left on the email server.";
            emailformat = 50;
            log.debug("Could not handle properly");
        }

        email = ((InternetAddress) m.getFrom()[0]).getAddress();
        name = ((InternetAddress) m.getFrom()[0]).getPersonal();
        replyTo = ((InternetAddress) m.getReplyTo()[0]).getAddress();
        sentDate = m.getSentDate();
        subject = m.getSubject();

        log.debug("Got message " + email + " " + name + " " + subject + " " + content);

        Criteria contcrit = new Criteria();
        contcrit.add(ContactPeer.EMAIL, (Object) email, Criteria.EQUAL);
        if (ContactPeer.doSelect(contcrit).size() > 0) {
            log.debug("From known contact");
            Contact myContact = (Contact) ContactPeer.doSelect(contcrit).get(0);
            entry.setCustomerId(myContact.getCustomerId());
            entry.setContactId(myContact.getContactId());
        } else {

            // find if customer exists
            Criteria criteria = new Criteria();
            criteria.add(CustomerPeer.EMAIL, (Object) email, Criteria.EQUAL);
            if (CustomerPeer.doSelect(criteria).size() > 0) {
                log.debug("From known customer");
                Customer myDistrib = (Customer) CustomerPeer.doSelect(criteria).get(0);
                entry.setCustomerId(myDistrib.getCustomerId());
            }

        }

        entry.setInboxEventCode(getTempCode());
        entry.setEventType(10);
        entry.setEventChannel(10);
        entry.setEmailFormat(emailformat);
        entry.setSubject(subject);
        entry.setSenderEmail(email);
        entry.setSenderName(name);
        entry.setSenderReplyTo(replyTo);
        entry.setSentTime(sentDate);
        entry.setBody(content);
        entry.setIssuedDate(new Date());
        entry.setCreatedBy("system");
        entry.setCreated(new Date());
        entry.setModifiedBy("system");
        entry.setModified(new Date());

        Connection conn = Transaction.begin(InboxEventPeer.DATABASE_NAME);
        boolean success = false;
        try {
            entry.save(conn);
            entry.setInboxEventCode(getRowCode("IE", entry.getInboxEventId()));
            entry.save(conn);
            Transaction.commit(conn);
            success = true;
        } finally {
            log.debug("Succcessfully stored in db: " + success);
            if (!success)
                Transaction.safeRollback(conn);
        }

        if (emailformat != 50) {
            m.setFlag(Flags.Flag.DELETED, true);
        }
    }

    // Close pop3 connection
    folder.close(true);
    store.close();

}

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

protected void filterContent(final Message message) throws MessagingException {
    if (StringUtils.isEmpty(getPartIndex())) {
        try {/*from   w w w  .  j  a  v  a  2 s  . com*/
            defineAsCurrentResponse(IOUtils.toString(message.getInputStream()), message.getContentType());
            return;
        } catch (IOException e) {
            throw new MessagingException("Error extracting message: " + e.getMessage());
        }
    }
    final int partIndex = ConversionUtil.convertToInt(getPartIndex(), 0);
    try {
        final Object content = message.getContent();
        if (content instanceof Multipart) {
            extractMultiPartMessage((Multipart) content, partIndex);
            return;
        }
        extractSimpleMessage((String) content, partIndex);
    } catch (IOException e) {
        LOG.error("Error processing email message: ", e);
        throw new MessagingException("Error processing email message: " + e.getMessage());
    }
}

From source file:org.apache.camel.component.mail.MailBinding.java

/**
 * Extracts the body from the Mail message
 *//* w  w  w  .  ja v  a  2s .  co  m*/
public Object extractBodyFromMail(Exchange exchange, MailMessage mailMessage) {
    Message message = mailMessage.getMessage();
    try {
        return message.getContent();
    } catch (Exception e) {
        // try to fix message in case it has an unsupported encoding in the Content-Type header
        UnsupportedEncodingException uee = ObjectHelper.getException(UnsupportedEncodingException.class, e);
        if (uee != null) {
            LOG.debug("Unsupported encoding detected: " + uee.getMessage());
            try {
                String contentType = message.getContentType();
                String type = ObjectHelper.before(contentType, "charset=");
                if (type != null) {
                    // try again with fixed content type
                    LOG.debug("Trying to extract mail message again with fixed Content-Type: " + type);
                    // Since message is read-only, we need to use a copy
                    MimeMessage messageCopy = new MimeMessage((MimeMessage) message);
                    messageCopy.setHeader("Content-Type", type);
                    Object body = messageCopy.getContent();
                    // If we got this far, our fix worked...
                    // Replace the MailMessage's Message with the copy
                    mailMessage.setMessage(messageCopy);
                    return body;
                }
            } catch (Exception e2) {
                // fall through and let original exception be thrown
            }
        }

        throw new RuntimeCamelException("Failed to extract body due to: " + e.getMessage() + ". Exchange: "
                + exchange + ". Message: " + message, e);
    }
}

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

/**
 * Retrieve attachment from mail//from   ww  w  .j  av  a2  s . c om
 * 
 * @param m
 * @return
 */
private FileUtil getAttachment(Message m) {

    FileUtil file = null;

    try {

        Object content = m.getContent();
        if (content instanceof Multipart) {
            file = handleMultipart((Multipart) content, false);

        } else {
            file = handlePart(m, false);

        }

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

    }

    return file;

}

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:org.apache.camel.component.mail.MailBinding.java

/**
 * Parses the attachments of the given mail message and adds them to the map
 *
 * @param  message  the mail message with attachments
 * @param  map      the map to add found attachments (attachmentFilename is the key)
 *//*from   w w  w.java 2  s . c om*/
public void extractAttachmentsFromMail(Message message, Map<String, DataHandler> map)
        throws javax.mail.MessagingException, IOException {

    LOG.trace("Extracting attachments +++ start +++");

    Object content = message.getContent();
    if (content instanceof Multipart) {
        extractAttachmentsFromMultipart((Multipart) content, map);
    } else if (content != null) {
        LOG.trace("No attachments to extract as content is not Multipart: " + content.getClass().getName());
    }

    LOG.trace("Extracting attachments +++ done +++");
}

From source file:server.MailPop3Expert.java

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

    while (store.isConnected()) {
        try {/*  www  . j a  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:org.apache.usergrid.management.EmailFlowIT.java

@Test
public void testCreateOrganizationAndAdminWithConfirmationAndActivation() throws Exception {
    setup.set(PROPERTIES_SYSADMIN_APPROVES_ADMIN_USERS, "true");
    setup.set(PROPERTIES_NOTIFY_ADMIN_OF_ACTIVATION, "true");
    setup.set(PROPERTIES_SYSADMIN_APPROVES_ORGANIZATIONS, "false");
    setup.set(PROPERTIES_ADMIN_USERS_REQUIRE_CONFIRMATION, "true");
    setup.set(PROPERTIES_SYSADMIN_EMAIL, "sysadmin-2@mockserver.com");

    OrganizationOwnerInfo org_owner = createOwnerAndOrganization(ORGANIZATION_NAME_2, "test-user-2",
            "Test User", "test-user-2@mockserver.com", "testpassword", false, false);
    assertNotNull(org_owner);/*from  w ww . j av  a2  s. co m*/

    List<Message> user_inbox = Mailbox.get("test-user-2@mockserver.com");

    assertFalse(user_inbox.isEmpty());

    Message confirmation = user_inbox.get(0);
    assertEquals("User Account Confirmation: test-user-2@mockserver.com", confirmation.getSubject());

    String token = getTokenFromMessage(confirmation);
    LOG.info(token);

    ActivationState state = setup.getMgmtSvc().handleConfirmationTokenForAdminUser(org_owner.owner.getUuid(),
            token);
    assertEquals(ActivationState.CONFIRMED_AWAITING_ACTIVATION, state);

    confirmation = user_inbox.get(1);
    String body = ((MimeMultipart) confirmation.getContent()).getBodyPart(0).getContent().toString();
    Boolean subbedEmailed = StringUtils.contains(body, "$");

    assertFalse(subbedEmailed);

    assertEquals("User Account Confirmed", confirmation.getSubject());

    List<Message> sysadmin_inbox = Mailbox.get("sysadmin-2@mockserver.com");
    assertFalse(sysadmin_inbox.isEmpty());

    Message activation = sysadmin_inbox.get(0);
    assertEquals("Request For Admin User Account Activation test-user-2@mockserver.com",
            activation.getSubject());

    token = getTokenFromMessage(activation);
    LOG.info(token);

    state = setup.getMgmtSvc().handleActivationTokenForAdminUser(org_owner.owner.getUuid(), token);
    assertEquals(ActivationState.ACTIVATED, state);

    Message activated = user_inbox.get(2);
    assertEquals("User Account Activated", activated.getSubject());

    MockImapClient client = new MockImapClient("mockserver.com", "test-user-2", "somepassword");
    client.processMail();
}

From source file:org.apache.usergrid.rest.management.AdminUsersIT.java

/**
 * Extract token from mocked inbox message.
 * @param msg/*w  ww .j a v a2 s . co  m*/
 * @return
 * @throws IOException
 * @throws MessagingException
 */
private String getTokenFromMessage(Message msg) throws IOException, MessagingException {
    String body = ((MimeMultipart) msg.getContent()).getBodyPart(0).getContent().toString();
    return StringUtils.substringAfterLast(body, "token=");
}