Example usage for javax.mail Message getSubject

List of usage examples for javax.mail Message getSubject

Introduction

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

Prototype

public abstract String getSubject() throws MessagingException;

Source Link

Document

Get the subject of this message.

Usage

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  ww.  j a  va 2 s  .  com*/
    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:org.usergrid.management.EmailFlowTest.java

@Test
public void testAppUserActivationResetpwdMail() throws Exception {

    ApplicationInfo appInfo = management.getApplicationInfo("test-organization/test-app");
    User user = setupAppUser(appInfo.getId(), "registration_requires_admin_approval", Boolean.TRUE,
            "testAppUserMailUrl", "testAppUserMailUrl@test.com", false);

    String subject = "Request For User Account Activation testAppUserMailUrl@test.com";
    String activation_url = String.format(properties.getProperty(PROPERTIES_USER_ACTIVATION_URL),
            "test-organization", "test-app", user.getUuid().toString());
    //Activation//from  w w w. j a  v  a  2 s .  c  om
    management.startAppUserActivationFlow(appInfo.getId(), user);

    List<Message> inbox = org.jvnet.mock_javamail.Mailbox.get("test@usergrid.com");
    assertFalse(inbox.isEmpty());
    MockImapClient client = new MockImapClient("usergrid.com", "test", "somepassword");
    client.processMail();

    // subject ok
    Message account_activation_message = inbox.get(0);
    assertEquals(subject, account_activation_message.getSubject());

    // activation url ok
    String mailContent = (String) ((MimeMultipart) account_activation_message.getContent()).getBodyPart(1)
            .getContent();
    logger.info(mailContent);
    assertTrue(StringUtils.contains(mailContent, activation_url));

    // token ok
    String token = getTokenFromMessage(account_activation_message);
    logger.info(token);
    ActivationState activeState = management.handleActivationTokenForAppUser(appInfo.getId(), user.getUuid(),
            token);
    assertEquals(ActivationState.ACTIVATED, activeState);

    subject = "Password Reset";
    String reset_url = String.format(properties.getProperty(PROPERTIES_USER_RESETPW_URL), "test-organization",
            "test-app", user.getUuid().toString());
    // reset_pwd
    management.startAppUserPasswordResetFlow(appInfo.getId(), user);

    inbox = org.jvnet.mock_javamail.Mailbox.get("testAppUserMailUrl@test.com");
    assertFalse(inbox.isEmpty());
    client = new MockImapClient("test.com", "testAppUserMailUrl", "somepassword");
    client.processMail();

    // subject ok
    Message password_reset_message = inbox.get(1);
    assertEquals(subject, password_reset_message.getSubject());

    // resetpwd url ok
    mailContent = (String) ((MimeMultipart) password_reset_message.getContent()).getBodyPart(1).getContent();
    logger.info(mailContent);
    assertTrue(StringUtils.contains(mailContent, reset_url));

    // token ok
    token = getTokenFromMessage(password_reset_message);
    logger.info(token);
    assertTrue(management.checkPasswordResetTokenForAppUser(appInfo.getId(), user.getUuid(), token));

    // ensure revoke works
    management.revokeAccessTokenForAppUser(token);
    assertFalse(management.checkPasswordResetTokenForAppUser(appInfo.getId(), user.getUuid(), token));
}

From source file:org.apache.usergrid.management.EmailFlowIT.java

/** Tests to make sure a normal user must be activated by the admin after confirmation. */
@Test// w  w  w  .  j  av  a 2s .c  o  m
public void testAppUserConfirmationMail() throws Exception {
    String orgName = this.getClass().getName();
    String appName = name.getMethodName();
    String userName = "Test User";
    String email = "test-user-45@mockserver.com";
    String passwd = "testpassword";
    OrganizationOwnerInfo orgOwner;

    orgOwner = createOwnerAndOrganization(orgName, appName, userName, email, passwd, false, false);
    assertNotNull(orgOwner);

    ApplicationInfo app = setup.getMgmtSvc().createApplication(orgOwner.getOrganization().getUuid(), appName);
    assertNotNull(app);
    enableEmailConfirmation(app.getId());
    enableAdminApproval(app.getId());
    User user = setupAppUser(app.getId(), "testAppUserConfMail", "testAppUserConfMail@test.com", true);

    String subject = "User Account Confirmation: testAppUserConfMail@test.com";
    String urlProp = setup.get(PROPERTIES_USER_CONFIRMATION_URL);
    String confirmation_url = String.format(urlProp, orgName, appName, user.getUuid().toString());

    // request confirmation
    setup.getMgmtSvc().startAppUserActivationFlow(app.getId(), user);

    List<Message> inbox = Mailbox.get("testAppUserConfMail@test.com");
    assertFalse(inbox.isEmpty());
    MockImapClient client = new MockImapClient("test.com", "testAppUserConfMail", "somepassword");
    client.processMail();

    // subject ok
    Message confirmation = inbox.get(0);
    assertEquals(subject, confirmation.getSubject());

    // confirmation url ok
    String mailContent = (String) ((MimeMultipart) confirmation.getContent()).getBodyPart(1).getContent();
    LOG.info(mailContent);
    assertTrue(StringUtils.contains(mailContent, confirmation_url));

    // token ok
    String token = getTokenFromMessage(confirmation);
    LOG.info(token);
    ActivationState activeState = setup.getMgmtSvc().handleConfirmationTokenForAppUser(app.getId(),
            user.getUuid(), token);
    assertEquals(ActivationState.CONFIRMED_AWAITING_ACTIVATION, activeState);
}

From source file:at.molindo.notify.channel.mail.AbstractMailClient.java

@Override
public synchronized void send(Dispatch dispatch) throws MailException {

    Message message = dispatch.getMessage();

    String recipient = dispatch.getParams().get(MailChannel.RECIPIENT);
    String recipientName = dispatch.getParams().get(MailChannel.RECIPIENT_NAME);
    String subject = message.getSubject();

    try {/*from w w  w .  j av a2  s  . com*/
        MimeMessage mm = new MimeMessage(getSmtpSession(recipient)) {
            @Override
            protected void updateMessageID() throws MessagingException {
                String domain = _from.getAddress();
                int idx = _from.getAddress().indexOf('@');
                if (idx >= 0) {
                    domain = domain.substring(idx + 1);
                }
                setHeader("Message-ID", "<" + UUID.randomUUID() + "@" + domain + ">");
            }
        };
        mm.setFrom(_from);
        mm.setSender(_from);

        InternetAddress replyTo = getReplyTo();
        if (replyTo != null) {
            mm.setReplyTo(new Address[] { replyTo });
        }
        mm.setHeader("X-Mailer", "molindo-notify");
        mm.setSentDate(new Date());

        mm.setRecipient(RecipientType.TO,
                new InternetAddress(recipient, recipientName, CharsetUtils.UTF_8.displayName()));
        mm.setSubject(subject, CharsetUtils.UTF_8.displayName());

        if (_format == Format.HTML) {
            if (message.getType() == Type.TEXT) {
                throw new MailException("can't send HTML mail from TEXT message", false);
            }
            mm.setText(message.getHtml(), CharsetUtils.UTF_8.displayName(), "html");
        } else if (_format == Format.TEXT || _format == Format.MULTI && message.getType() == Type.TEXT) {
            mm.setText(message.getText(), CharsetUtils.UTF_8.displayName());
        } else if (_format == Format.MULTI) {
            MimeBodyPart html = new MimeBodyPart();
            html.setText(message.getHtml(), CharsetUtils.UTF_8.displayName(), "html");

            MimeBodyPart text = new MimeBodyPart();
            text.setText(message.getText(), CharsetUtils.UTF_8.displayName());

            /*
             * The formats are ordered by how faithful they are to the
             * original, with the least faithful first and the most faithful
             * last. (http://en.wikipedia.org/wiki/MIME#Alternative)
             */
            MimeMultipart mmp = new MimeMultipart();
            mmp.setSubType("alternative");

            mmp.addBodyPart(text);
            mmp.addBodyPart(html);

            mm.setContent(mmp);
        } else {
            throw new NotifyRuntimeException(
                    "unexpected format (" + _format + ") or type (" + message.getType() + ")");
        }

        send(mm);

    } catch (final MessagingException e) {
        throw new MailException(
                "could not send mail from " + _from + " to " + recipient + " (" + toErrorMessage(e) + ")", e,
                isTemporary(e));
    } catch (UnsupportedEncodingException e) {
        throw new RuntimeException("utf8 unknown?", e);
    }
}

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 w  w .  j a  va 2s.  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.jahia.modules.gateway.mail.MailToJSONImpl.java

@Handler
public void handleExchange(Exchange exchange) {
    assert exchange.getIn() instanceof MailMessage;
    long timer = System.currentTimeMillis();
    final Message mailMessage = ((MailMessage) exchange.getIn()).getMessage();
    try {//  w w w  .  ja va  2s  . c o m
        String subject = mailMessage.getSubject();

        Address[] from = mailMessage.getFrom();
        Address sender = from != null && from.length > 0 ? from[0] : null;

        if (logger.isDebugEnabled()) {
            logger.debug("Got message from {} with the subject: {}", sender, subject);
        }

        // Parse content and multipart
        MailContent mailContent = new MailContent();
        parseMailMessage(mailMessage, mailContent);

        if (logger.isTraceEnabled()) {
            logger.trace("Parsed message body:\n{} \n\nFiles:\n{}", mailContent.getBody(),
                    mailContent.getFiles());
        }

        Pattern matchingPattern = null;
        MailDecoder decoder = decoders.get("<default>"); // get the default decoder if any

        decodersLoop: for (MailDecoder examinee : decoders.values()) {
            List<Pattern> patterns = examinee.getPatterns();
            if (patterns != null) {
                for (Pattern regexp : patterns) {
                    if (matches(mailContent, regexp)) {
                        decoder = examinee;
                        matchingPattern = regexp;
                        break decodersLoop;
                    }
                }
            }
        }

        if (decoder != null) {
            if (logger.isDebugEnabled()) {
                if (matchingPattern == null) {
                    logger.debug("Using default decoder '{}' ({}) for the e-mail",
                            new String[] { decoder.getKey(), decoder.getClass().getName() });
                } else {
                    logger.debug("Using decoder '{}' ({}) for the e-mail matching pattern \"{}\"",
                            new String[] { decoder.getKey(), decoder.getClass().getName(),
                                    matchingPattern.pattern() });
                }
            }

            boolean deleteFiles = false;

            String jsonOutput = null;
            try {
                jsonOutput = decoder.decode(matchingPattern, mailContent, mailMessage);
            } catch (Exception e) {
                logger.error("Error processing e-mail message with subject \"" + subject + "\" using decoder "
                        + decoder.getKey() + " from " + sender + ", Cause: " + e.getMessage(), e);
                deleteFiles = true;
            }
            if (StringUtils.isNotBlank(jsonOutput)) {
                if (logger.isTraceEnabled()) {
                    logger.trace("Decoder output is:\n{}", jsonOutput);
                }
                DefaultMessage in = new DefaultMessage();
                in.setBody(jsonOutput);
                exchange.setOut(in);
            } else {
                deleteFiles = true;
            }

            if (deleteFiles && !mailContent.getFiles().isEmpty()) {
                for (FileItem file : mailContent.getFiles()) {
                    FileUtils.deleteQuietly(file.getFile());
                }
            }
        } else {
            if (logger.isDebugEnabled()) {
                logger.debug("Skipping e-mail as no decoder configured to match subject: {}\n", subject);
            }
        }
        if (logger.isDebugEnabled()) {
            logger.debug("Message from {} with the subject '{}' processed in {} ms",
                    new Object[] { sender, subject, System.currentTimeMillis() - timer });
        }
    } catch (Exception e) {
        logger.error(e.getMessage(), e);
    }
}

From source file:org.apache.usergrid.management.EmailFlowIT.java

@Test
public void testAppUserActivationResetpwdMail() throws Exception {
    String orgName = this.getClass().getName() + "1";
    String appName = name.getMethodName();
    String userName = "Test User";
    String email = "test-user-4@mockserver.com";
    String passwd = "testpassword";
    OrganizationOwnerInfo orgOwner;//  w  w  w .  j a v  a2s .  co m

    orgOwner = createOwnerAndOrganization(orgName, appName, userName, email, passwd, false, false);
    assertNotNull(orgOwner);

    ApplicationInfo app = setup.getMgmtSvc().createApplication(orgOwner.getOrganization().getUuid(), appName);
    enableAdminApproval(app.getId());
    User user = setupAppUser(app.getId(), "testAppUserMailUrl", "testAppUserMailUrl@test.com", false);

    String subject = "Request For User Account Activation testAppUserMailUrl@test.com";
    String activation_url = String.format(setup.get(PROPERTIES_USER_ACTIVATION_URL), orgName, appName,
            user.getUuid().toString());

    // Activation
    setup.getMgmtSvc().startAppUserActivationFlow(app.getId(), user);

    List<Message> inbox = Mailbox.get(email);
    assertFalse(inbox.isEmpty());
    MockImapClient client = new MockImapClient("usergrid.com", "test", "somepassword");
    client.processMail();

    // subject ok
    Message activation = inbox.get(0);
    assertEquals(subject, activation.getSubject());

    // activation url ok
    String mailContent = (String) ((MimeMultipart) activation.getContent()).getBodyPart(1).getContent();
    LOG.info(mailContent);
    assertTrue(StringUtils.contains(mailContent, activation_url));

    // token ok
    String token = getTokenFromMessage(activation);
    LOG.info(token);
    ActivationState activeState = setup.getMgmtSvc().handleActivationTokenForAppUser(app.getId(),
            user.getUuid(), token);
    assertEquals(ActivationState.ACTIVATED, activeState);

    subject = "Password Reset";
    String reset_url = String.format(setup.get(PROPERTIES_USER_RESETPW_URL), orgName, appName,
            user.getUuid().toString());

    // reset_pwd
    setup.getMgmtSvc().startAppUserPasswordResetFlow(app.getId(), user);

    inbox = Mailbox.get("testAppUserMailUrl@test.com");
    assertFalse(inbox.isEmpty());
    client = new MockImapClient("test.com", "testAppUserMailUrl", "somepassword");
    client.processMail();

    // subject ok
    Message reset = inbox.get(1);
    assertEquals(subject, reset.getSubject());

    // resetpwd url ok
    mailContent = (String) ((MimeMultipart) reset.getContent()).getBodyPart(1).getContent();
    LOG.info(mailContent);
    assertTrue(StringUtils.contains(mailContent, reset_url));

    // token ok
    token = getTokenFromMessage(reset);
    LOG.info(token);
    assertTrue(setup.getMgmtSvc().checkPasswordResetTokenForAppUser(app.getId(), user.getUuid(), token));

    // ensure revoke works
    setup.getMgmtSvc().revokeAccessTokenForAppUser(token);
    assertFalse(setup.getMgmtSvc().checkPasswordResetTokenForAppUser(app.getId(), user.getUuid(), token));
}

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

@Test
public void testPopulateWelcomeMessage() 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", "Welcome",
            "welcome_email.vm", _session);

    Assert.assertEquals("Auction Alert <test@test.com>", message.getFrom()[0].toString());
    Assert.assertEquals("Welcome", message.getSubject());
    Assert.assertEquals(_WELCOME_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.usergrid.management.EmailFlowTest.java

@Test
public void testCreateOrganizationAndAdminWithConfirmationOnly() throws Exception {

    properties.setProperty(PROPERTIES_SYSADMIN_APPROVES_ADMIN_USERS, "false");
    properties.setProperty(PROPERTIES_SYSADMIN_APPROVES_ORGANIZATIONS, "false");
    properties.setProperty(PROPERTIES_ADMIN_USERS_REQUIRE_CONFIRMATION, "true");
    properties.setProperty(PROPERTIES_SYSADMIN_EMAIL, "sysadmin-1@mockserver.com");
    properties.setProperty(PROPERTIES_NOTIFY_ADMIN_OF_ACTIVATION, "true");

    OrganizationOwnerInfo org_owner = management.createOwnerAndOrganization(ORGANIZATION_NAME, "test-user-1",
            "Test User", "test-user-1@mockserver.com", "testpassword", false, false);
    assertNotNull(org_owner);/*from w w  w. j  a va 2s.com*/

    List<Message> inbox = org.jvnet.mock_javamail.Mailbox.get("test-user-1@mockserver.com");

    assertFalse(inbox.isEmpty());

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

    Message account_confirmation_message = inbox.get(0);
    assertEquals("User Account Confirmation: test-user-1@mockserver.com",
            account_confirmation_message.getSubject());

    String token = getTokenFromMessage(account_confirmation_message);
    logger.info(token);

    assertEquals(ActivationState.ACTIVATED,
            management.handleConfirmationTokenForAdminUser(org_owner.owner.getUuid(), token));

    Message account_activation_message = inbox.get(1);
    assertEquals("User Account Activated", account_activation_message.getSubject());

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

From source file:org.webguitoolkit.messagebox.mail.MailChannel.java

/**
 * // ww  w. ja  v  a 2  s  . co  m
 */
@Override
public List<IMessage> receive(boolean clear) {
    List<IMessage> result = new ArrayList<IMessage>();

    try {
        String user = properties.getProperty("pop3.login.user");
        String password = properties.getProperty("pop3.login.password");

        String SSL_FACTORY = "javax.net.ssl.SSLSocketFactory";

        Properties pop3Props = new Properties();

        pop3Props.setProperty("mail.pop3.socketFactory.class", SSL_FACTORY);
        pop3Props.setProperty("mail.pop3.socketFactory.fallback", "false");
        pop3Props.setProperty("mail.pop3.port", properties.getProperty("pop3.port"));
        pop3Props.setProperty("mail.pop3.socketFactory.port", properties.getProperty("pop3.port"));

        URLName url = new URLName("pop3", properties.getProperty("pop3.host"),
                Integer.valueOf(properties.getProperty("pop3.port")), "", user, password);

        Session session = Session.getInstance(pop3Props, null);
        Store store = new POP3SSLStore(session, url);
        store.connect();

        // Open the Folder
        Folder folder = store.getDefaultFolder();
        folder = folder.getFolder("INBOX");

        if (folder == null) {
            throw new RuntimeException("Invalid folder INBOX");
        }

        // try to open read/write and if that fails try read-only
        try {
            folder.open(Folder.READ_WRITE);
        } catch (MessagingException ex) {
            folder.open(Folder.READ_ONLY);
        }

        int count = folder.getMessageCount();
        // Message numbers start at 1
        for (int i = 1; i <= count; i++) {
            // Get a message by its sequence number
            Message m = folder.getMessage(i);
            Address[] from = m.getFrom();
            String type = from[0].getType();

            IMessage message = new MailMessage(from[0].toString(), this, m.getSubject(), getContent(m));

            result.add(message);

            // delete message ?
            if (clear)
                m.setFlag(Flags.Flag.DELETED, true);
        }

        // "true" actually deletes flagged messages from folder
        folder.close(clear);
        store.close();
    } catch (Exception e) {
        throw new RuntimeException(e);
    }
    return result;
}