Example usage for javax.mail Message getHeader

List of usage examples for javax.mail Message getHeader

Introduction

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

Prototype

public String[] getHeader(String header_name) throws MessagingException;

Source Link

Document

Get all the headers for this header name.

Usage

From source file:it.greenvulcano.gvesb.virtual.smtp.SMTPCallOperationTest.java

/**
 * Tests email send/*  ww w . j av  a2  s. c o  m*/
 *
 * @throws Exception
 *         if any error occurs
 */
public final void testSendEmailDynamicDest() throws Exception {
    Node node = XMLConfig.getNode("GVCore.xml", "//*[@name='SendEmailDynamicDest']");
    CallOperation op = new SMTPCallOperation();
    op.init(node);

    GVBuffer gvBuffer = new GVBuffer(TEST_SYSTEM, TEST_SERVICE);
    gvBuffer.setObject(TEST_MESSAGE);

    gvBuffer.setProperty("GV_SMTP_TO", "test1@gv.com");
    gvBuffer.setProperty("GV_SMTP_CC", "test2@gv.com");
    gvBuffer.setProperty("GV_SMTP_BCC", "test3@gv.com");

    op.perform(gvBuffer);

    Message[] messages = server.getReceivedMessages();
    assertEquals(3, messages.length);
    Message email = messages[0];
    Multipart mp = (Multipart) email.getContent();
    assertEquals("Notifica SendEmailDynamicDest", email.getSubject());
    assertEquals(TEST_MESSAGE_1, GreenMailUtil.getBody(mp.getBodyPart(0)));

    System.out.println("---------MAIL DUMP: START");
    System.out.println("Headers:\n" + GreenMailUtil.getHeaders(email));
    System.out.println("---------");
    System.out.println("Body:\n" + GreenMailUtil.getBody(email));
    System.out.println("---------MAIL DUMP: END");
    assertEquals("Notifica SendEmailDynamicDest", email.getHeader("Subject")[0]);
    assertEquals("test1@gv.com", email.getHeader("To")[0]);
    assertEquals("test2@gv.com", email.getHeader("Cc")[0]);
}

From source file:it.greenvulcano.gvesb.virtual.smtp.SMTPCallOperationTest.java

/**
 * Tests email send//from w w  w .  j  av  a  2  s .com
 *
 * @throws Exception
 *         if any error occurs
 */
public final void testSendEmailBufferAttach() throws Exception {
    Node node = XMLConfig.getNode("GVCore.xml", "//*[@name='SendEmailBufferAttach']");
    CallOperation op = new SMTPCallOperation();
    op.init(node);

    GVBuffer gvBuffer = new GVBuffer(TEST_SYSTEM, TEST_SERVICE);
    gvBuffer.setObject(TEST_MESSAGE);

    op.perform(gvBuffer);

    Message[] messages = server.getReceivedMessages();
    assertEquals(1, messages.length);
    Message email = messages[0];
    Multipart mp = (Multipart) email.getContent();
    assertEquals("Notifica SendEmailBufferAttach", email.getSubject());
    assertEquals(TEST_MESSAGE_1, GreenMailUtil.getBody(mp.getBodyPart(0)));

    System.out.println("---------MAIL DUMP: START");
    System.out.println("Headers:\n" + GreenMailUtil.getHeaders(email));
    System.out.println("---------");
    System.out.println("Body:\n" + GreenMailUtil.getBody(mp.getBodyPart(0)));
    System.out.println("---------MAIL DUMP: END");
    assertEquals("Notifica SendEmailBufferAttach", email.getHeader("Subject")[0]);
    assertEquals("Current Data", mp.getBodyPart(1).getFileName());
}

From source file:net.fenyo.mail4hotspot.service.AdvancedServicesImpl.java

private void _processMails(final String username, final boolean headerOnly) {
    Long session_id = null;//from www . j av a 2  s  .c  om
    boolean should_remove_user_id_processing = false;

    final GeneralServices.UserAndAccounts userAndAccounts = generalServices.getUserAndAccounts(username);

    if (!validAccount(userAndAccounts.accounts)) {
        log.warn("invalid number of accounts");
        return;
    }

    try {
        synchronized (userIdsProcessing) {
            if (userIdsProcessing.contains(userAndAccounts.user.getId())) {
                //               log.warn("account is currently processed");
                return;
            } else {
                should_remove_user_id_processing = true;
                userIdsProcessing.add(userAndAccounts.user.getId());
            }
        }

        final Account account = userAndAccounts.accounts.iterator().next();

        // on supprime les mails qui sont plus vieux que la marque et rcuprs il y a plus d'un certain temps
        // s'il n'y a pas de marque, on ne supprime rien
        generalServices.removeOldMessages(account);

        final List<String> msgids = generalServices.getMsgIds(account);
        final List<String> msgids_older_than_mark = generalServices.getMessageIdsOlderThanMark(account);
        // final String message_id_mark = generalServices.getMessageIdMark(account);

        //         if (message_id_mark != null) {
        //            // trouver comment se servir de "assert(msgids.contains(message_id_mark));"
        //            if (msgids.contains(message_id_mark) == false) {
        //               log.error("assertion failed");
        //               System.exit(1);
        //            }
        //         }

        final MailManager manager = new MailManager();
        try {
            manager.connectToProvider(account.getProvider(), account.getUsername(), account.getPassword());

            if (manager.getMessages() == null)
                log.error("manager.getMessages() == null");
            else {
                final Message[] messages = manager.getMessages();
                boolean marked = false;
                String first_message_id = null;

                for (int msg_idx = messages.length - 1; (msg_idx >= 0)
                        && (messages.length - msg_idx <= MAX_MAILS_PER_SESSION); msg_idx--) {
                    final Message message = messages[msg_idx];

                    final String[] msgidHeaders = message.getHeader("Message-Id");
                    if (msgidHeaders == null || msgidHeaders.length == 0)
                        log.warn("ignoring message without Message-Id");
                    else {
                        if (first_message_id == null)
                            first_message_id = msgidHeaders[0];

                        if (!msgids.contains(msgidHeaders[0])) {
                            // this is a new mail

                            final InboxMail inboxMail = new InboxMail();

                            inboxMail.setUnread(true);
                            inboxMail.setHeaderOnly(headerOnly);

                            // Message-Id
                            inboxMail.setMessageId(
                                    GenericTools.truncate(msgidHeaders[0], InboxMail.MAX_MESG_ID_LENGTH));

                            // From
                            final Address[] from_addr = message.getFrom();
                            if (from_addr != null) {
                                final StringBuffer from_addresses = new StringBuffer();
                                for (int i = 0; i < from_addr.length; i++) {
                                    if (i > 0)
                                        from_addresses.append("; ");
                                    from_addresses.append(from_addr[0].toString());
                                }
                                inboxMail.setFromAddr(GenericTools.truncate(from_addr[0].toString(),
                                        InboxMail.MAX_ADDRESS_LENGTH));
                            }

                            // To
                            final Address[] to_addr = message.getRecipients(RecipientType.TO);
                            if (to_addr != null) {
                                final StringBuffer to_addresses = new StringBuffer();
                                for (int i = 0; i < to_addr.length; i++) {
                                    if (i > 0)
                                        to_addresses.append("; ");
                                    to_addresses.append(to_addr[0].toString());
                                }
                                inboxMail.setToAddr(GenericTools.truncate(to_addr[0].toString(),
                                        InboxMail.MAX_ADDRESS_LENGTH));
                            }

                            // Cc
                            final Address[] cc_addr = message.getRecipients(RecipientType.CC);
                            if (cc_addr != null) {
                                final StringBuffer cc_addresses = new StringBuffer();
                                for (int i = 0; i < cc_addr.length; i++) {
                                    if (i > 0)
                                        cc_addresses.append("; ");
                                    cc_addresses.append(cc_addr[0].toString());
                                }
                                inboxMail.setCcAddr(GenericTools.truncate(cc_addr[0].toString(),
                                        InboxMail.MAX_ADDRESS_LENGTH));
                            }

                            // Subject
                            if (message.getSubject() != null)
                                inboxMail.setSubject(GenericTools.truncate(message.getSubject(),
                                        InboxMail.MAX_SUBJECT_LENGTH));

                            // Dates
                            inboxMail.setSentDate(message.getSentDate());
                            inboxMail.setReceivedDate(new java.util.Date());

                            if (!headerOnly) {
                                // Content
                                try {
                                    inboxMail.setContent(
                                            GenericTools.truncate(manager.getMessageContentString(message),
                                                    InboxMail.MAX_CONTENT_LENGTH));
                                } catch (final IOException ex) {
                                    ex.printStackTrace();
                                } catch (final MessagingException ex) {
                                    ex.printStackTrace();
                                }
                            }

                            // persists entity
                            if (headerOnly) {
                                // header only == objectif : ce qui est dj dans la bote mail du provider ne sera jamais rcupr
                                // le plus rcent mail (on commence par les plus rcents et on marque le 1er), qu'on n'a pas dj vu (car on ne passe ici que pour les mails pas dj vus), est marqu
                                if (!marked) {
                                    session_id = generalServices.saveInboxMailMark(account, inboxMail,
                                            session_id);
                                    marked = true;
                                } else
                                    session_id = generalServices.saveInboxMail(account, inboxMail, session_id);
                            } else {
                                session_id = generalServices.saveInboxMail(account, inboxMail, session_id);
                            }
                        } else {
                            // on a dj ce message-id

                            if (headerOnly) {
                                // header only == objectif : ce qui est dj dans la bote mail du provider ne sera jamais rcupr
                                // le plus rcent mail (on commence par les plus rcents et on marque le 1er), qu'on n'a pas dj vu (car on ne passe ici que pour les mails pas dj vus), est marqu
                                if (!marked) {
                                    generalServices.saveMark(account, msgidHeaders[0]);
                                    marked = true;
                                }
                            } else {
                                // pas en mode header only => on vrifie si on a rencontr la marque

                                //                           if (msgidHeaders[0].equals(message_id_mark)) {
                                // marque rencontre => on arrte
                                //                              break;
                                //                           }
                                //                           log.debug("msgids_older_than_mark size:" + msgids_older_than_mark.size());
                                if (msgids_older_than_mark != null
                                        && msgids_older_than_mark.contains(msgidHeaders[0])) {
                                    // marque rencontre => on arrte
                                    break;
                                }
                            }
                        }

                    }
                }

                // aprs la boucle sur les messages (donc soit sortie du break car rencontre de la marque, soit boucle termine)
                // on met donc  jour la marque avec le 1er message (le plus rcent rcupr)
                if (!headerOnly && first_message_id != null)
                    generalServices.saveMark(account, first_message_id);

            }
        } catch (final AuthenticationFailedException ex) {
            log.info("TRACE: authentication failure;" + username + ";" + ex.toString() + ";");
            generalServices.saveProviderError(account, ex.toString());
        } catch (final MessagingException ex) {
            ex.printStackTrace();
        } finally {
            try {
                manager.disconnect();
            } catch (final MessagingException ex) {
                ex.printStackTrace();
            }
        }

    } finally {
        synchronized (userIdsProcessing) {
            if (should_remove_user_id_processing && userIdsProcessing.contains(userAndAccounts.user.getId()))
                userIdsProcessing.remove(userAndAccounts.user.getId());
        }
    }
}

From source file:com.ephesoft.dcma.mail.service.MailServiceImpl.java

@Override
public void mailOnError(final String subject, final Message previousMailMessage, final String batchClassName,
        final String userName, final String mailTemplatePath) throws DCMAApplicationException {
    LOGGER.debug("Creating  mailMetaData odr mail or error.");
    if (null != subject && null != batchClassName && null != userName && null != previousMailMessage) {
        final MailMetaData metaData = new MailMetaData();
        metaData.setFromAddress(fromMail);
        metaData.setFromName(fromMail);/*from  w  w  w. ja  va2 s. c  om*/
        metaData.setSubject(subject);
        metaData.setToAddresses(new ArrayList<String>(StringUtils.commaDelimitedListToSet(toMail)));
        final MailContentModel model = new MailContentModel();
        model.add(MailConstants.BATCH_CLASS, batchClassName);
        model.add(MailConstants.USER_ID, userName);
        try {
            String ccString = Arrays.toString(previousMailMessage.getHeader(MailConstants.CC))
                    .replace(MailConstants.OPENING_BRACKET, MailConstants.SPACE)
                    .replace(MailConstants.CLOSING_BRACKET, MailConstants.EMPTY_STRING);
            String toString = Arrays.toString(previousMailMessage.getHeader(MailConstants.TO))
                    .replace(MailConstants.OPENING_BRACKET, MailConstants.SPACE)
                    .replace(MailConstants.CLOSING_BRACKET, MailConstants.EMPTY_STRING);

            // below date format will be used to format date string received
            // from mail header. Mail header can provide a lot more
            // info.
            SimpleDateFormat simpleDateFormat = new SimpleDateFormat(MailConstants.DATE_FORMAT);
            model.add(MailConstants.SUBJECT, previousMailMessage.getSubject());
            model.add(MailConstants.FROM,
                    Arrays.toString(previousMailMessage.getHeader(MailConstants.FROM))
                            .replace(MailConstants.OPENING_BRACKET, MailConstants.SPACE)
                            .replace(MailConstants.CLOSING_BRACKET, ""));
            model.add(MailConstants.TO,
                    toString.equalsIgnoreCase(MailConstants.NULL_STRING) ? MailConstants.EMPTY_STRING
                            : toString);
            model.add(MailConstants.CC,
                    ccString.equalsIgnoreCase(MailConstants.NULL_STRING) ? MailConstants.EMPTY_STRING
                            : ccString);
            model.add(MailConstants.RECEIVED_DATE,
                    simpleDateFormat
                            .parseObject(previousMailMessage.getHeader(MailConstants.DATE_STRING)[0].toString())
                            .toString());
        } catch (javax.mail.MessagingException mailException) {
            LOGGER.error("Error encountered while extarcting info from previos mail object", mailException);
            throw new DCMAApplicationException(
                    "Error encountered while extarcting infor from previos mail object", mailException);
        } catch (java.text.ParseException parseException) {
            LOGGER.error(
                    "Error encountered while parsing date extracted from mail header of previos mail object",
                    parseException);
            throw new DCMAApplicationException(
                    "Error encountered while parsing received date from previos mail object", parseException);
        }
        LOGGER.debug(
                EphesoftStringUtil.concatenate("Batch Class Name: ", batchClassName, "  UserName: ", userName));
        sendTextMailWithClasspathTemplate(metaData, mailTemplatePath, model, previousMailMessage);
    } else {
        LOGGER.error(
                "Either or all of the following values are null. Error notification mail cann't be sent. \n Subject,BatchClassName, UserName");
    }
}

From source file:uidmsgshow.java

public static void dumpEnvelope(Message m) throws Exception {
    System.out.println("This is the message envelope");
    System.out.println("---------------------------");
    Address[] a;//  www .jav  a  2  s .co  m
    // FROM 
    if ((a = m.getFrom()) != null) {
        for (int j = 0; j < a.length; j++)
            System.out.println("FROM: " + a[j].toString());
    }

    // TO
    if ((a = m.getRecipients(Message.RecipientType.TO)) != null) {
        for (int j = 0; j < a.length; j++)
            System.out.println("TO: " + a[j].toString());
    }

    // SUBJECT
    System.out.println("SUBJECT: " + m.getSubject());

    // DATE
    Date d = m.getSentDate();
    System.out.println("SendDate: " + (d != null ? d.toString() : "UNKNOWN"));

    // SIZE
    System.out.println("Size: " + m.getSize());

    // 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]);
    }
    System.out.println("FLAGS = " + sb.toString());

    // X-MAILER
    String[] hdrs = m.getHeader("X-Mailer");
    if (hdrs != null)
        System.out.println("X-Mailer: " + hdrs[0]);
    else
        System.out.println("X-Mailer NOT available");
}

From source file:uidmsgshow.java

public static void dumpEnvelope(Message m) throws Exception {
    System.out.println("This is the message envelope");
    System.out.println("---------------------------");
    Address[] a;//w  w w.ja va  2  s .c o  m
    // FROM
    if ((a = m.getFrom()) != null) {
        for (int j = 0; j < a.length; j++)
            System.out.println("FROM: " + a[j].toString());
    }

    // TO
    if ((a = m.getRecipients(Message.RecipientType.TO)) != null) {
        for (int j = 0; j < a.length; j++)
            System.out.println("TO: " + a[j].toString());
    }

    // SUBJECT
    System.out.println("SUBJECT: " + m.getSubject());

    // DATE
    Date d = m.getSentDate();
    System.out.println("SendDate: " + (d != null ? d.toString() : "UNKNOWN"));

    // SIZE
    System.out.println("Size: " + m.getSize());

    // 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]);
    }
    System.out.println("FLAGS = " + sb.toString());

    // X-MAILER
    String[] hdrs = m.getHeader("X-Mailer");
    if (hdrs != null)
        System.out.println("X-Mailer: " + hdrs[0]);
    else
        System.out.println("X-Mailer NOT available");
}

From source file:com.naryx.tagfusion.cfm.mail.cfPOP3.java

private void populateMessage(cfSession _Session, Message thisMessage, cfQueryResultData popData, boolean GetAll,
        File attachmentDir, Folder _parent) throws Exception {
    popData.addRow(1);/*from  w w w . jav  a  2 s .  c o  m*/
    int Row = popData.getNoRows();

    Date date = thisMessage.getSentDate();
    if (date != null) {
        cfDateData cfdate = new cfDateData(date);
        cfdate.setPOPDate();
        popData.setCell(Row, 1, cfdate);
    } else {
        popData.setCell(Row, 1, new cfStringData(""));
    }

    popData.setCell(Row, 2, new cfStringData(formatAddress(thisMessage.getFrom())));
    popData.setCell(Row, 3, new cfNumberData(thisMessage.getMessageNumber()));
    popData.setCell(Row, 4, new cfStringData(formatAddress(thisMessage.getReplyTo())));
    popData.setCell(Row, 5, new cfStringData(thisMessage.getSubject()));
    popData.setCell(Row, 6,
            new cfStringData(formatAddress(thisMessage.getRecipients(Message.RecipientType.CC))));
    popData.setCell(Row, 7,
            new cfStringData(formatAddress(thisMessage.getRecipients(Message.RecipientType.TO))));
    String[] msgid = thisMessage.getHeader("Message-ID");
    popData.setCell(Row, 8, new cfStringData(msgid != null ? msgid[0] : ""));
    popData.setCell(Row, 9, new cfStringData(getMessageUID(_parent, thisMessage)));
    popData.setCell(Row, 10, new cfStringData(formatHeader(thisMessage)));

    if (GetAll) {
        retrieveBody(_Session, thisMessage, popData, Row, attachmentDir);
    }
}

From source file:MainClass.java

public static void dumpEnvelope(Message m) throws Exception {
    pr("This is the message envelope");
    pr("---------------------------");
    Address[] a;/*w  w w .  j a  va 2 s  .  c  o m*/
    // FROM
    if ((a = m.getFrom()) != null) {
        for (int j = 0; j < a.length; j++)
            pr("FROM: " + 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:msgshow.java

public static void dumpEnvelope(Message m) throws Exception {
    pr("This is the message envelope");
    pr("---------------------------");
    Address[] a;/*from w  w  w  .j  a v  a 2 s . c o  m*/
    // 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.midori.confluence.plugin.mail2news.Mail2NewsJob.java

/**
 * Get the space key and subsequently the space from the recipient
 * email address.// ww  w. j  a  va  2  s  .c o m
 * The space key is extracted in the form "email+spacekey@domain.net". If the email
 * address does not contain a "+spacekey", then the application tests if it can
 * find a spacekey which is equivalent to the local part of the email address.
 *
 * @param message The mail message from which to extract the space key.
 * @return Returns the space
 * @throws Exception Throws an exception if the space key cannot be extracted or the space cannot be found.
 */
private Space getSpaceFromAddress(Message message) throws Exception {
    /* list for deferred space keys (see below) */
    List<Space> deferredSpaceKeys = new LinkedList<Space>();

    /* get the To: email addresses */
    Address[] recipientTo = message.getRecipients(Message.RecipientType.TO);

    /* get the CC: email addresses */
    Address[] recipientCc = message.getRecipients(Message.RecipientType.CC);

    /* merge To and CC addresses into one array */
    if (recipientTo == null) // FIXME this should be seriously rewritten
    {
        recipientTo = new Address[0];
    }
    if (recipientCc == null) {
        recipientCc = new Address[0];
    }
    Address[] recipient = new Address[recipientTo.length + recipientCc.length];

    System.arraycopy(recipientTo, 0, recipient, 0, recipientTo.length);
    System.arraycopy(recipientCc, 0, recipient, recipientTo.length, recipientCc.length);

    /* check if we have any address */
    if (recipient.length == 0) {
        /* no recipient */
        this.log.error("No recipient found in email.");
        /* throw an error */
        throw new Exception("No recipient found in email.");
    }

    /* loop through all addresses until we found one where we can extract
     * a space key */
    for (int i = 0; i < recipient.length; i++) {
        /* retrieve the email address */
        String emailAddress;
        if (recipient[i] instanceof InternetAddress) {
            emailAddress = ((InternetAddress) recipient[i]).getAddress();
        } else {
            emailAddress = recipient[i].toString();
        }

        /* extract the wiki space name */
        Pattern pattern = Pattern.compile("(.+?)([a-zA-Z0-9]+\\+[a-zA-Z0-9]+)@(.+?)");
        Matcher matcher = pattern.matcher(emailAddress);
        String spaceKey = "";
        boolean defer = false;
        if (matcher.matches()) {
            String tmp = matcher.group(2);
            spaceKey = tmp.substring(tmp.indexOf('+') + 1);
        } else {
            /* the email address is not in the form "aaaa+wikispace@bbb"
            /* fallback: test if there exists a space with a spacekey equal to the
             *           local part of the email address.
             */
            spaceKey = emailAddress.substring(0, emailAddress.indexOf('@'));
            defer = true;
        }

        /* check if the space exists */
        Space space = spaceManager.getSpace(spaceKey);
        if (space == null) {
            // fall back to look up a personal space
            space = spaceManager.getPersonalSpace(spaceKey);
        }
        if (space == null) {
            /* could not find the space specified in the email address */
            this.log.info("Unknown space key: " + spaceKey);
            /* try the next address if possible. */
            continue;
        }

        /* check if it is a fallback space key */
        if (defer) {
            /* add to the list of fallback spaces. if we don't find another
             * space in the form addr+spacekey@..., then we take the first one
             * of the fallback spaces */
            deferredSpaceKeys.add(space);
        } else {
            return space;
        }
    }

    /* we did not find a space in the form addr+spacekey@domain.net.
     * check for a fallback space */
    if (deferredSpaceKeys.size() > 0) {
        /* take the first fallback space */
        Space s = deferredSpaceKeys.get(0);
        return s;
    }

    /* did not find any space, not even a fallback key */

    /* Concat the to headers into one string for the error message */
    String[] toHeaders = message.getHeader("To");
    String toString = "";
    for (int j = 0; j < toHeaders.length; j++) {
        toString = toString.concat(toHeaders[j]);
        if (j < (toHeaders.length - 1)) {
            toString = toString.concat(" / ");
        }
    }
    throw new Exception("Could not extract space key from any of the To: addresses: " + toString);
}