Example usage for javax.mail Message getRecipients

List of usage examples for javax.mail Message getRecipients

Introduction

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

Prototype

public abstract Address[] getRecipients(RecipientType type) throws MessagingException;

Source Link

Document

Get all the recipient addresses of the given type.

Usage

From source file:org.exist.xquery.modules.mail.MessageListFunctions.java

private Sequence getMessageListAsXML(Sequence[] args, Sequence contextSequence) throws XPathException {
    Message[] msgList;/*from   w ww .j  a v a2  s .  com*/
    Sequence ret = Sequence.EMPTY_SEQUENCE;

    // was a msgList handle specified?
    if (args[0].isEmpty()) {
        throw (new XPathException(this, "Message List handle not specified"));
    }

    // get the MessageList
    long msgListHandle = ((IntegerValue) args[0].itemAt(0)).getLong();
    msgList = MailModule.retrieveMessageList(context, msgListHandle);
    if (msgList == null) {
        throw (new XPathException(this, "Invalid Message List handle specified"));
    }

    if (msgList.length > 0) {

        boolean includeHeaders = args[1].effectiveBooleanValue();

        MemTreeBuilder builder = context.getDocumentBuilder();

        builder.startDocument();
        builder.startElement(new QName("messages", MailModule.NAMESPACE_URI, MailModule.PREFIX), null);
        builder.addAttribute(new QName("count", null, null), String.valueOf(msgList.length));

        try {
            for (int i = 0; i < msgList.length; i++) {
                Message message = msgList[i];

                builder.startElement(new QName("message", MailModule.NAMESPACE_URI, MailModule.PREFIX), null);

                builder.addAttribute(new QName("number", null, null),
                        String.valueOf(message.getMessageNumber()));

                // Sent Date
                if (message.getSentDate() != null) {
                    builder.startElement(new QName("sent", MailModule.NAMESPACE_URI, MailModule.PREFIX), null);
                    builder.characters(formatDate(message.getSentDate()));
                    builder.endElement();
                }

                // Received Date
                if (message.getReceivedDate() != null) {
                    builder.startElement(new QName("received", MailModule.NAMESPACE_URI, MailModule.PREFIX),
                            null);
                    builder.characters(formatDate(message.getReceivedDate()));
                    builder.endElement();
                }

                // From
                if (message.getFrom() != null) {
                    builder.startElement(new QName("from", MailModule.NAMESPACE_URI, MailModule.PREFIX), null);
                    builder.characters(message.getFrom()[0].toString());
                    builder.endElement();
                }

                // Recipients
                builder.startElement(new QName("recipients", MailModule.NAMESPACE_URI, MailModule.PREFIX),
                        null);
                // To Recipients
                Address[] toAddresses = message.getRecipients(Message.RecipientType.TO);
                if (toAddresses != null) {
                    for (Address to : toAddresses) {
                        builder.startElement(
                                new QName("recipient", MailModule.NAMESPACE_URI, MailModule.PREFIX), null);
                        builder.addAttribute(new QName("type", null, null), "to");
                        builder.characters(to.toString());
                        builder.endElement();
                    }
                }

                // cc Recipients
                Address[] ccAddresses = message.getRecipients(Message.RecipientType.CC);
                if (ccAddresses != null) {
                    for (Address ccAddress : ccAddresses) {
                        builder.startElement(
                                new QName("recipient", MailModule.NAMESPACE_URI, MailModule.PREFIX), null);
                        builder.addAttribute(new QName("type", null, null), "cc");
                        builder.characters(ccAddress.toString());
                        builder.endElement();
                    }
                }

                // bcc Recipients
                Address[] bccAddresses = message.getRecipients(Message.RecipientType.BCC);
                if (bccAddresses != null) {
                    for (Address bccAddress : bccAddresses) {
                        builder.startElement(
                                new QName("recipient", MailModule.NAMESPACE_URI, MailModule.PREFIX), null);
                        builder.addAttribute(new QName("type", null, null), "bcc");
                        builder.characters(bccAddress.toString());
                        builder.endElement();
                    }
                }
                builder.endElement();

                // Flags

                Flags flags = message.getFlags();
                Flags.Flag[] systemFlags = flags.getSystemFlags();
                String[] userFlags = flags.getUserFlags();

                if (systemFlags.length > 0 || userFlags.length > 0) {
                    builder.startElement(new QName("flags", MailModule.NAMESPACE_URI, MailModule.PREFIX), null);

                    for (Flags.Flag systemFlag : systemFlags) {
                        if (systemFlag == Flags.Flag.ANSWERED) {
                            builder.startElement(new QName("flag", MailModule.NAMESPACE_URI, MailModule.PREFIX),
                                    null);
                            builder.addAttribute(new QName("type", null, null), "answered");
                            builder.endElement();
                        } else if (systemFlag == Flags.Flag.DELETED) {
                            builder.startElement(new QName("flag", MailModule.NAMESPACE_URI, MailModule.PREFIX),
                                    null);
                            builder.addAttribute(new QName("type", null, null), "deleted");
                            builder.endElement();
                        } else if (systemFlag == Flags.Flag.DRAFT) {
                            builder.startElement(new QName("flag", MailModule.NAMESPACE_URI, MailModule.PREFIX),
                                    null);
                            builder.addAttribute(new QName("type", null, null), "draft");
                            builder.endElement();
                        } else if (systemFlag == Flags.Flag.FLAGGED) {
                            builder.startElement(new QName("flag", MailModule.NAMESPACE_URI, MailModule.PREFIX),
                                    null);
                            builder.addAttribute(new QName("type", null, null), "flagged");
                            builder.endElement();
                        } else if (systemFlag == Flags.Flag.RECENT) {
                            builder.startElement(new QName("flag", MailModule.NAMESPACE_URI, MailModule.PREFIX),
                                    null);
                            builder.addAttribute(new QName("type", null, null), "recent");
                            builder.endElement();
                        } else if (systemFlag == Flags.Flag.SEEN) {
                            builder.startElement(new QName("flag", MailModule.NAMESPACE_URI, MailModule.PREFIX),
                                    null);
                            builder.addAttribute(new QName("type", null, null), "seen");
                            builder.endElement();
                        }
                    }

                    for (String userFlag : userFlags) {
                        builder.startElement(new QName("flag", MailModule.NAMESPACE_URI, MailModule.PREFIX),
                                null);
                        builder.addAttribute(new QName("type", null, null), "user");
                        builder.addAttribute(new QName("value", null, null), userFlag);
                        builder.endElement();
                    }

                    builder.endElement();
                }

                // Headers

                if (includeHeaders) {
                    Enumeration headers = message.getAllHeaders();

                    if (headers.hasMoreElements()) {
                        builder.startElement(new QName("headers", MailModule.NAMESPACE_URI, MailModule.PREFIX),
                                null);

                        while (headers.hasMoreElements()) {
                            Header header = (Header) headers.nextElement();

                            builder.startElement(
                                    new QName("header", MailModule.NAMESPACE_URI, MailModule.PREFIX), null);
                            builder.addAttribute(new QName("name", null, null), header.getName());
                            builder.addAttribute(new QName("value", null, null), header.getValue());
                            builder.endElement();
                        }

                        builder.endElement();
                    }
                }

                // Subject
                builder.startElement(new QName("subject", MailModule.NAMESPACE_URI, MailModule.PREFIX), null);
                builder.characters(message.getSubject());
                builder.endElement();

                builder.endElement();
            }
        } catch (MessagingException me) {
            throw (new XPathException(this, "Failed to retrieve messages from list", me));
        }

        builder.endElement();

        ret = (NodeValue) builder.getDocument().getDocumentElement();
    }

    return (ret);
}

From source file:org.jahia.services.workflow.jbpm.custom.email.JBPMMailProducer.java

public Collection<Message> produce(final WorkItem workItem) {
    if (!ServicesRegistry.getInstance().getMailService().isEnabled()) {
        return Collections.emptyList();
    }/*from   w  ww .j a v  a2 s.  c  o m*/
    final Map<String, Object> vars = workItem.getParameters();
    Locale locale = (Locale) vars.get("locale");
    String templateKey = (String) vars.get("templateKey");
    MailTemplate template = null;

    if (templateKey != null) {
        if (locale != null) {
            template = (mailTemplateRegistry.getTemplate(templateKey + "." + locale.toString()));
            if (template == null) {
                template = (mailTemplateRegistry.getTemplate(templateKey + "." + locale.getLanguage()));
            }
        }
        if (template == null) {
            template = mailTemplateRegistry.getTemplate(templateKey);
        }
    }

    if (template != null) {
        final MailTemplate usedTemplate = template;
        try {
            return JCRTemplate.getInstance().doExecuteWithSystemSessionAsUser(null, Constants.EDIT_WORKSPACE,
                    locale, new JCRCallback<Collection<Message>>() {
                        public Collection<Message> doInJCR(JCRSessionWrapper session)
                                throws RepositoryException {
                            try {
                                scriptEngine = ScriptEngineUtils.getInstance()
                                        .getEngineByName(usedTemplate.getLanguage());
                                bindings = null;
                                Message email = instantiateEmail();
                                fillFrom(usedTemplate, email, workItem, session);
                                fillRecipients(usedTemplate, email, workItem, session);
                                fillSubject(usedTemplate, email, workItem, session);
                                fillContent(usedTemplate, email, workItem, session);
                                Address[] addresses = email.getRecipients(Message.RecipientType.TO);
                                if (addresses != null && addresses.length > 0) {
                                    return Collections.singleton(email);
                                } else {
                                    addresses = email.getRecipients(Message.RecipientType.BCC);
                                    if (addresses != null && addresses.length > 0) {
                                        return Collections.singleton(email);
                                    }
                                    addresses = email.getRecipients(Message.RecipientType.CC);
                                    if (addresses != null && addresses.length > 0) {
                                        return Collections.singleton(email);
                                    }
                                    return Collections.emptyList();
                                }
                            } catch (Exception e) {
                                logger.error("Cannot produce mail", e);
                            }
                            return Collections.emptyList();
                        }
                    });
        } catch (RepositoryException e) {
            logger.error("Cannot produce mail", e);
        }
    }
    return Collections.emptyList();
}

From source file:org.jahia.services.workflow.jbpm.JBPMMailProducer.java

public Collection<Message> produce(final Execution execution) {
    final Map<String, Object> vars = ((ExecutionImpl) execution).getVariables();
    Locale locale = (Locale) vars.get("locale");

    if (templateKey != null) {
        MailTemplate template = null;//from w w  w. j a v  a2s  . co  m
        MailTemplateRegistry templateRegistry = ((ProcessEngine) SpringContextSingleton
                .getBean("processEngine")).get(MailTemplateRegistry.class);
        if (locale != null) {
            template = (templateRegistry.getTemplate(templateKey + "." + locale.toString()));
            if (template == null) {
                template = (templateRegistry.getTemplate(templateKey + "." + locale.getLanguage()));
            }
        }
        if (template == null) {
            template = templateRegistry.getTemplate(templateKey);
        }
        setTemplate(template);
    }

    if (ServicesRegistry.getInstance().getMailService().isEnabled() && getTemplate() != null) {
        try {
            return JCRTemplate.getInstance().doExecuteWithSystemSession(null, "default", locale,
                    new JCRCallback<Collection<Message>>() {
                        public Collection<Message> doInJCR(JCRSessionWrapper session)
                                throws RepositoryException {
                            try {
                                scriptEngine = ScriptEngineUtils.getInstance()
                                        .getEngineByName(getTemplate().getLanguage());
                                bindings = null;
                                Message email = instantiateEmail();
                                fillFrom(email, execution, session);
                                fillRecipients(email, execution, session);
                                fillSubject(email, execution, session);
                                fillContent(email, execution, session);
                                Address[] addresses = email.getRecipients(Message.RecipientType.TO);
                                if (addresses != null && addresses.length > 0) {
                                    return Collections.singleton(email);
                                } else {
                                    return Collections.emptyList();
                                }
                            } catch (MessagingException e) {
                                logger.error(e.getMessage(), e);
                            } catch (ScriptException e) {
                                logger.error(e.getMessage(), e);
                            }
                            return Collections.emptyList();
                        }
                    });
        } catch (RepositoryException e) {
            logger.error(e.getMessage(), e);
        }
    }
    return Collections.emptyList();
}

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

protected void addRecipientProperty(MuleMessage muleMessage, Message mailMessage, RecipientType recipientType,
        String property) throws MessagingException {
    MimeMessage mimeMessage = null;/* ww  w.j  a  va 2 s .co  m*/
    if (mailMessage instanceof MimeMessage) {
        mimeMessage = (MimeMessage) mailMessage;
    }

    try {
        Address[] recipients = mailMessage.getRecipients(recipientType);
        muleMessage.setProperty(property, MailUtils.mailAddressesToString(recipients), PropertyScope.INBOUND);
    } catch (MessagingException e) {
        if (mimeMessage != null) {
            String[] header = mimeMessage.getHeader(recipientType.toString());
            String recipients = StringUtils.join(header, ", ");
            muleMessage.setProperty(property, recipients, PropertyScope.INBOUND);
        }
    }
}

From source file:org.nuclos.server.ruleengine.RuleInterface.java

/**
 *
 * @param pop3Host/*from   ww  w. j  a  v a2  s . c  om*/
 * @param pop3Port
 * @param pop3User
 * @param pop3Password
 * @param remove
 * @return
 * @throws NuclosFatalRuleException
 */
public List<NuclosMail> getMails(String pop3Host, String pop3Port, final String pop3User,
        final String pop3Password, boolean remove) throws NuclosFatalRuleException {
    try {
        Properties properties = new Properties();
        properties.setProperty("mail.pop3.host", pop3Host);
        properties.setProperty("mail.pop3.port", pop3Port);
        properties.setProperty("mail.pop3.auth", "true");
        properties.setProperty("mail.pop3.socketFactory.class", "javax.net.DefaultSocketFactory");

        Session session = Session.getInstance(properties, new javax.mail.Authenticator() {
            @Override
            protected PasswordAuthentication getPasswordAuthentication() {
                return new PasswordAuthentication(pop3User, pop3Password);
            }
        });

        session.setDebug(true);
        Store store = session.getStore("pop3");
        store.connect();

        Folder folder = store.getFolder("INBOX");
        if (remove) {
            folder.open(Folder.READ_WRITE);
        } else {
            folder.open(Folder.READ_ONLY);
        }

        List<NuclosMail> result = new ArrayList<NuclosMail>();

        Message message[] = folder.getMessages();
        for (int i = 0; i < message.length; i++) {
            Message m = message[i];
            NuclosMail mail = new NuclosMail();
            logger.debug("Received mail: From: " + Arrays.toString(m.getFrom()) + "; To: "
                    + Arrays.toString(m.getAllRecipients()) + "; ContentType: " + m.getContentType()
                    + "; Subject: " + m.getSubject() + "; Sent: " + m.getSentDate());

            Address[] senders = m.getFrom();
            if (senders.length == 1 && senders[0] instanceof InternetAddress) {
                mail.setFrom(((InternetAddress) senders[0]).getAddress());
            } else {
                mail.setFrom(Arrays.toString(m.getFrom()));
            }
            mail.setTo(Arrays.toString(m.getRecipients(RecipientType.TO)));
            mail.setSubject(m.getSubject());

            if (m.isMimeType("text/plain")) {
                mail.setMessage((String) m.getContent());
            } else {
                Multipart mp = (Multipart) m.getContent();
                for (int j = 0; j < mp.getCount(); j++) {
                    Part part = mp.getBodyPart(j);
                    String disposition = part.getDisposition();
                    MimeBodyPart mimePart = (MimeBodyPart) part;
                    logger.debug(
                            "Disposition: " + disposition + "; Part ContentType: " + mimePart.getContentType());

                    if (disposition == null
                            && (mimePart.isMimeType("text/plain") || mimePart.isMimeType("text/html"))) {
                        mail.setMessage((String) mimePart.getDataHandler().getContent());
                    }
                }
                getAttachments(mp, mail);
            }

            result.add(mail);

            if (remove) {
                m.setFlag(Flags.Flag.DELETED, true);
            }
        }

        if (remove) {
            folder.close(true);
        } else {
            folder.close(false);
        }

        store.close();

        return result;
    } catch (Exception e) {
        throw new NuclosFatalRuleException(e);
    }
}

From source file:org.nuxeo.ecm.platform.mail.listener.action.ExtractMessageInformationAction.java

@Override
public boolean execute(ExecutionContext context) {
    bodyContent = "";

    boolean copyMessage = Boolean.parseBoolean(Framework.getProperty(COPY_MESSAGE, "false"));

    try {/*from  w w  w.j  a va2  s.c  om*/
        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 && copyMessage) {
            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;
        }

        // Subject
        String subject = message.getSubject();
        if (subject != null) {
            subject = subject.trim();
        }
        if (subject == null || "".equals(subject)) {
            subject = "<Unknown>";
        }
        context.put(SUBJECT_KEY, subject);

        // Sender
        try {
            Address[] from = message.getFrom();
            String sender = null;
            String senderEmail = null;
            if (from != null) {
                Address addr = from[0];
                if (addr instanceof InternetAddress) {
                    InternetAddress iAddr = (InternetAddress) addr;
                    senderEmail = iAddr.getAddress();
                    sender = iAddr.getPersonal() + " <" + senderEmail + ">";
                } else {
                    sender += addr.toString();
                    senderEmail = sender;
                }
            }
            context.put(SENDER_KEY, sender);
            context.put(SENDER_EMAIL_KEY, senderEmail);
        } catch (AddressException ae) {
            // try to parse sender from header instead
            String[] values = message.getHeader("From");
            if (values != null) {
                context.put(SENDER_KEY, values[0]);
            }
        }
        // Sending date
        context.put(SENDING_DATE_KEY, message.getSentDate());

        // Recipients
        try {
            Address[] to = message.getRecipients(Message.RecipientType.TO);
            Collection<String> recipients = new ArrayList<String>();
            if (to != null) {
                for (Address addr : to) {
                    if (addr instanceof InternetAddress) {
                        InternetAddress iAddr = (InternetAddress) addr;
                        if (iAddr.getPersonal() != null) {
                            recipients.add(iAddr.getPersonal() + " <" + iAddr.getAddress() + ">");
                        } else {
                            recipients.add(iAddr.getAddress());
                        }
                    } else {
                        recipients.add(addr.toString());
                    }
                }
            }
            context.put(RECIPIENTS_KEY, recipients);
        } catch (AddressException ae) {
            // try to parse recipient from header instead
            Collection<String> recipients = getHeaderValues(message, Message.RecipientType.TO.toString());
            context.put(RECIPIENTS_KEY, recipients);
        }

        // CC recipients

        try {
            Address[] toCC = message.getRecipients(Message.RecipientType.CC);
            Collection<String> ccRecipients = new ArrayList<String>();
            if (toCC != null) {
                for (Address addr : toCC) {
                    if (addr instanceof InternetAddress) {
                        InternetAddress iAddr = (InternetAddress) addr;
                        ccRecipients.add(iAddr.getPersonal() + " " + iAddr.getAddress());
                    } else {
                        ccRecipients.add(addr.toString());
                    }
                }
            }
            context.put(CC_RECIPIENTS_KEY, ccRecipients);

        } catch (AddressException ae) {
            // try to parse ccRecipient from header instead
            Collection<String> ccRecipients = getHeaderValues(message, Message.RecipientType.CC.toString());
            context.put(CC_RECIPIENTS_KEY, ccRecipients);
        }
        String[] messageIdHeader = message.getHeader("Message-ID");
        if (messageIdHeader != null) {
            context.put(MailCoreConstants.MESSAGE_ID_KEY, messageIdHeader[0]);
        }

        MimetypeRegistry mimeService = (MimetypeRegistry) context.getInitialContext().get(MIMETYPE_SERVICE_KEY);

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

        // String[] cte = message.getHeader("Content-Transfer-Encoding");

        // process content
        getAttachmentParts(message, subject, mimeService, context);

        context.put(TEXT_KEY, bodyContent);

        return true;
    } catch (MessagingException | IOException e) {
        log.error(e, e);
    }
    return false;
}

From source file:org.socraticgrid.displaymaildata.DisplayMailDataHandler.java

/**
 * IN USE// w  w  w  .  j  a  v a2s.co  m
 * 
 * @param request
 * @return
 * @throws Exception
 */
public GetMessageDetailResponseType getMessageDetail(GetMessageDetailRequestType request) throws Exception {
    System.out.println("===> DMD.getMessageDetail: Looking for msgId=" + request.getMessageId());
    System.out.println("===> DMD.getMessageDetail: request patientId=" + request.getPatientId());
    System.out.println("===> DMD.getMessageDetail: request    userId=" + request.getUserId());

    GetMessageDetailResponseType response = new GetMessageDetailResponseType();

    IMAPFolder msgFolder = null;
    IMAPSSLStore sslStore = null;
    Properties prop = initializeMailProperties();
    Session session = Session.getDefaultInstance(prop);

    //------------------------------------------------------------------
    // When patientId is given, access must be from EMR Inbox.
    //      Get email msgs from Patient's email account.
    // Else
    //      Get email msgs from logged in user's email account.
    //------------------------------------------------------------------
    ContactDTO contact = null;
    String userType = "";
    String[] access = new String[2];

    if (!CommonUtil.strNullorEmpty(request.getPatientId())) {
        contact = contactDAO.findContact("uid=" + request.getPatientId()).get(0);
        userType = ITEM_ID_PATIENT;

    } else {
        contact = contactDAO.findContact("uid=" + request.getUserId()).get(0);
        userType = ITEM_ID_PROVIDER;
    }
    access = retrieveMailAccess(contact.getCommonName(), contact.getUid());

    try {
        session = Session.getInstance(new Properties());
        URLName urlName = new URLName(mailUrl);

        //--------------------------------------------
        //Get the sslStore and connect
        //--------------------------------------------
        sslStore = new IMAPSSLStore(session, urlName);
        sslStore.connect(host, access[0], access[1]);

        //--------------------------------------------
        // Set the originating folder.
        // Default to INBOX if not given.
        // Get and open the IMAP folder
        //--------------------------------------------
        String folderName = null;
        if (CommonUtil.strNullorEmpty(request.getLocation())) {
            folderName = "INBOX";
        } else {
            folderName = mapKmrLocationToImapFolder(request.getLocation(), this.host);
        }

        msgFolder = (IMAPFolder) sslStore.getFolder(folderName);
        msgFolder.open(Folder.READ_ONLY);

        //--------------------------------------------
        // Find the message by the given Message-ID
        //--------------------------------------------
        Message msg = this.findMsgByMessageId(msgFolder, request.getMessageId());

        if (msg == null) {
            String errmsg = "Msg NOT FOUND for Message-ID=" + request.getMessageId();
            System.out.println("===> getMessageDetail: " + errmsg);

            response.setSuccessStatus(false);
            response.setStatusMessage(errmsg);

        } else {
            //this.printMsgIdSubject(msg); //DBG printout
            System.out.println("===> getMessageDetail: Msg FOUND for Message-ID=" + request.getMessageId());

            //---------------------------------------------------
            // Extract "PATIENTID=" from body if present, so that
            // user does not see it.
            //---------------------------------------------------
            String content = fetchMsgContent(msg);

            if (content.startsWith("PATIENTID=")) {
                Scanner scanner = new Scanner(content);
                boolean first = true;
                StringBuilder sb = new StringBuilder();
                while (scanner.hasNextLine()) {
                    if (first) {
                        String[] parts = scanner.nextLine().split("=");
                        response.setPatientId(parts[1]);
                        first = false;
                    } else {
                        sb.append(scanner.nextLine());
                    }

                }
                response.getMessageDetail().add(sb.toString());
            } else {
                response.getMessageDetail().add(content);
            }

            // Adding patientId coming from the message header.
            //            if (msg.getHeader("X-PATIENTID") != null &&
            //                msg.getHeader("X-PATIENTID").length > 0) {
            //
            //                response.setPatientId(msg.getHeader("X-PATIENT_ID")[0]);
            //            }

            if (msg.getRecipients(Message.RecipientType.TO) != null) {
                for (Address a : msg.getRecipients(Message.RecipientType.TO)) {
                    String contactId = getContactIdFromEmail(a.toString());
                    response.getSentTo().add(contactId);

                    //System.out.println("DisplayMailDataHandler: TO="+ a.toString() +" ldap.cn="+ contactId);
                }
            }

            if (msg.getRecipients(Message.RecipientType.CC) != null) {
                for (Address a : msg.getRecipients(Message.RecipientType.CC)) {
                    String contactId = getContactIdFromEmail(a.toString());
                    response.getCCTo().add(contactId);

                    //System.out.println("DisplayMailDataHandler: CC="+ a.toString() +" ldap.cn="+ contactId);
                }
            }

            if (msg.getRecipients(Message.RecipientType.BCC) != null) {
                for (Address a : msg.getRecipients(Message.RecipientType.BCC)) {
                    String contactId = getContactIdFromEmail(a.toString());
                    response.getBCCTo().add(contactId);

                    //System.out.println("DisplayMailDataHandler: BCC="+ a.toString() +" ldap.cn="+ contactId);
                }
            }
            response.setSuccessStatus(true);
            response.setStatusMessage("");
        }

    } catch (Exception e) {
        response.setSuccessStatus(false);
        response.setStatusMessage(
                "Error getting message detail for user: " + access[0] + "\n[EXCEPTION] " + e.toString());
        e.printStackTrace();

    } finally {
        if (msgFolder != null) {
            try {
                msgFolder.close(false);
            } catch (Exception e) {
            }
        }

        if (sslStore != null) {
            try {
                sslStore.close();
            } catch (Exception e) {
            }
        }
    }

    return response;
}

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

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

From source file: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  www.  j a  v  a2s  .co 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"));
}