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: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 .j a  va  2s  .c  o m*/
    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:ch.entwine.weblounge.bridge.mail.MailAggregator.java

/**
 * Returns the subject of this message. If the message does not have a
 * <code>subject</code> field, an {@link IllegalArgumentException} is thrown.
 * /*w w w.j  av  a  2s .c  om*/
 * @param message
 *          the e-mail message
 * @return the subject
 * @throws MessagingException
 *           if reading the message's subject fails
 * @throws IllegalArgumentException
 *           if no subject can be found
 */
private String getSubject(Message message) throws MessagingException, IllegalArgumentException {
    String subject = message.getSubject();
    if (StringUtils.isBlank(subject))
        throw new MessagingException("Message has no subject");
    return subject;
}

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

/**
 * Import messages//w  w  w.ja va2  s.  c o m
 * 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);
            log.info("Subject: {}", msg.getSubject());
            log.info("From: {}", msg.getFrom());
            log.info("Received: {}", msg.getReceivedDate());
            log.info("Sent: {}", msg.getSentDate());
            com.openkm.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.beanfuse.notification.mail.AbstractMailNotifier.java

public void sendMessage(Message msg) throws NotificationException {
    // contruct a MailMessage
    MailMessage mailConext = null;// w  w w .  j  a va2  s.com
    if (msg instanceof MailMessage) {
        mailConext = (MailMessage) msg;
    } else {
        mailConext = new MailMessage();
        mailConext.setSubject(msg.getSubject());
        mailConext.setText(msg.getText());
        mailConext.setProperties(msg.getProperties());
        String[] to = new String[msg.getRecipients().size()];
        msg.getRecipients().toArray(to);
        mailConext.setTo(to);
    }

    MimeMessage mimeMsg = javaMailSender.createMimeMessage();
    try {
        mimeMsg.setSentDate(new Date());
        MimeMessageHelper messageHelper = new MimeMessageHelper(mimeMsg);
        messageHelper.setText(buildText(mailConext), Message.HTML.equals(mailConext.getContentType()));
        String subject = buildSubject(mailConext);
        messageHelper.setSubject(subject);
        messageHelper.setFrom(fromMailbox, fromName);
        addRecipient(mimeMsg, javax.mail.Message.RecipientType.TO, mailConext.getTo());
        addRecipient(mimeMsg, javax.mail.Message.RecipientType.CC, mailConext.getCc());
        addRecipient(mimeMsg, javax.mail.Message.RecipientType.BCC, mailConext.getBcc());
        beforeSend(mailConext, mimeMsg);
        if (mimeMsg.getAllRecipients() != null && ((Address[]) mimeMsg.getAllRecipients()).length > 0) {
            javaMailSender.send(mimeMsg);
            logger.info("mail sended from {} to {} with subject {}",
                    new Object[] { fromMailbox, mailConext.getRecipients(), subject });
        }
    } catch (AddressException ex) {
        throw new NotificationException("Exception while sending message.", ex);
    } catch (MessagingException ex) {
        throw new NotificationException("Exception while sending message.", ex);
    } catch (UnsupportedEncodingException ex) {
        throw new NotificationException("Exception while sending message.", ex);
    }
    afterSend(mailConext, mimeMsg);
}

From source file:com.intuit.tank.mail.TankMailer.java

private void logMsg(String host, Message m) {
    try {/*from  ww w.ja  va2 s  . com*/
        StringBuilder sb = new StringBuilder();
        sb.append("To: ").append(StringUtils.join(m.getAllRecipients(), ',')).append('\n');
        sb.append("From: ").append(StringUtils.join(m.getFrom(), ',')).append('\n');
        sb.append("Subject: ").append(m.getSubject()).append('\n');
        sb.append("Body: ").append(m.getContent()).append('\n');
        LOG.info("Sending email to server (" + host + "):\n" + sb.toString());
    } catch (Exception e) {
        LOG.error("Error generating log msg: " + e);
    }

}

From source file:org.biokoframework.http.scenario.ScenarioRunner.java

private String prettify(Message scenarioExecutionMessage) throws Exception {
    StringBuilder builder = new StringBuilder();
    builder.append("(\"").append(scenarioExecutionMessage.getSubject()).append("\" and \"")
            .append(escapeJava(scenarioExecutionMessage.getContent().toString())).append("\")");
    return builder.toString();
}

From source file:org.usergrid.management.EmailFlowTest.java

@Test
public void testAppUserConfirmationMail() throws Exception {

    ApplicationInfo appInfo = management.getApplicationInfo("test-organization/test-app");
    assertNotNull(appInfo);/*  www  .  j a  v a2  s  .  c o m*/
    User user = setupAppUser(appInfo.getId(), "registration_requires_email_confirmation", Boolean.TRUE,
            "testAppUserConfMail", "testAppUserConfMail@test.com", true);

    String subject = "User Account Confirmation: testAppUserConfMail@test.com";
    String confirmation_url = String.format(properties.getProperty(PROPERTIES_USER_CONFIRMATION_URL),
            "test-organization", "test-app", user.getUuid().toString());
    // confirmation
    management.startAppUserActivationFlow(appInfo.getId(), user);

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

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

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

    // token ok
    String token = getTokenFromMessage(account_confirmation_message);
    logger.info(token);
    ActivationState activeState = management.handleConfirmationTokenForAppUser(appInfo.getId(), user.getUuid(),
            token);
    assertEquals(ActivationState.CONFIRMED_AWAITING_ACTIVATION, activeState);

}

From source file:msgshow.java

public static void dumpEnvelope(Message m) throws Exception {
    pr("This is the message envelope");
    pr("---------------------------");
    Address[] a;/*from  w  w  w. j av  a  2s  .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 ww  w.  j  a va 2 s.  c  o m
 * @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:org.nuxeo.cm.mail.actionpipe.ExtractMessageInformation.java

@Override
@SuppressWarnings("deprecation")
public boolean execute(ExecutionContext context) throws MessagingException {
    File tmpOutput = null;/*from   w ww .  j a v  a2s  .  com*/
    OutputStream out = null;
    try {
        Message originalMessage = context.getMessage();
        if (log.isDebugEnabled()) {
            log.debug("Transforming message, original subject: " + originalMessage.getSubject());
        }

        // fully load the message before trying to parse to
        // override most of server bugs, see
        // http://java.sun.com/products/javamail/FAQ.html#imapserverbug
        Message message;
        if (originalMessage instanceof MimeMessage) {
            message = new MimeMessage((MimeMessage) originalMessage);
            if (log.isDebugEnabled()) {
                log.debug("Transforming message after full load: " + message.getSubject());
            }
        } else {
            // stuck with the original one
            message = originalMessage;
        }

        Address[] from = message.getFrom();
        if (from != null) {
            Address addr = from[0];
            if (addr instanceof InternetAddress) {
                InternetAddress iAddr = (InternetAddress) addr;
                context.put(SENDER_KEY, iAddr.getPersonal());
                context.put(SENDER_EMAIL_KEY, iAddr.getAddress());
            } else {
                context.put(SENDER_KEY, addr.toString());
            }
        }
        Date receivedDate = message.getReceivedDate();
        if (receivedDate == null) {
            // try to get header manually
            String[] dateHeader = message.getHeader("Date");
            if (dateHeader != null) {
                try {
                    long time = Date.parse(dateHeader[0]);
                    receivedDate = new Date(time);
                } catch (IllegalArgumentException e) {
                    // nevermind
                }
            }
        }

        if (receivedDate != null) {
            Calendar date = Calendar.getInstance();
            date.setTime(receivedDate);
            context.put(RECEPTION_DATE_KEY, date);
        }
        String subject = message.getSubject();
        if (subject != null) {
            subject = subject.trim();
        }
        if (subject == null || "".equals(subject)) {
            subject = "<Unknown>";
        }
        context.put(SUBJECT_KEY, subject);
        String[] messageIdHeader = message.getHeader("Message-ID");
        if (messageIdHeader != null) {
            context.put(MESSAGE_ID_KEY, messageIdHeader[0]);
        }

        // TODO: pass it through initial context
        MimetypeRegistry mimeService = (MimetypeRegistry) context.getInitialContext().get(MIMETYPE_SERVICE_KEY);
        if (mimeService == null) {
            log.error("Could not retrieve mimetype service");
        }

        // add all content as first blob
        tmpOutput = File.createTempFile("injectedEmail", ".eml");
        Framework.trackFile(tmpOutput, tmpOutput);
        out = new FileOutputStream(tmpOutput);
        message.writeTo(out);
        Blob blob = Blobs.createBlob(tmpOutput, MESSAGE_RFC822_MIMETYPE, null, subject + ".eml");

        List<Blob> blobs = new ArrayList<>();
        blobs.add(blob);
        context.put(ATTACHMENTS_KEY, blobs);

        // process content
        getAttachmentParts(message, subject, mimeService, context);
        return true;
    } catch (IOException e) {
        log.error(e);
    } finally {
        IOUtils.closeQuietly(out);
    }
    return false;
}