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:com.liferay.mail.imap.IMAPAccessor.java

public void storeEnvelopes(long folderId, Folder jxFolder, Message[] jxMessages) throws PortalException {

    StopWatch stopWatch = new StopWatch();

    stopWatch.start();//w w  w  .j  a va 2s  . c  o  m

    try {
        FetchProfile fetchProfile = new FetchProfile();

        fetchProfile.add(UIDFolder.FetchProfileItem.ENVELOPE);
        fetchProfile.add(UIDFolder.FetchProfileItem.FLAGS);
        fetchProfile.add(UIDFolder.FetchProfileItem.UID);

        jxFolder.fetch(jxMessages, fetchProfile);

        for (Message jxMessage : jxMessages) {
            String sender = InternetAddressUtil.toString(jxMessage.getFrom());
            String to = InternetAddressUtil.toString(jxMessage.getRecipients(RecipientType.TO));
            String cc = InternetAddressUtil.toString(jxMessage.getRecipients(RecipientType.CC));
            String bcc = InternetAddressUtil.toString(jxMessage.getRecipients(RecipientType.BCC));
            Date sentDate = jxMessage.getSentDate();
            String subject = jxMessage.getSubject();
            String flags = getFlags(jxMessage);
            long remoteMessageId = getUID(jxFolder, jxMessage);
            String contentType = jxMessage.getContentType();

            try {
                MessageLocalServiceUtil.getMessage(folderId, remoteMessageId);
            } catch (NoSuchMessageException nsme) {
                MessageLocalServiceUtil.addMessage(_user.getUserId(), folderId, sender, to, cc, bcc, sentDate,
                        subject, StringPool.BLANK, flags, remoteMessageId, contentType);
            }
        }

        com.liferay.mail.model.Folder folder = FolderLocalServiceUtil.getFolder(folderId);

        FolderLocalServiceUtil.updateFolder(folderId, folder.getFullName(), folder.getDisplayName(),
                jxFolder.getMessageCount());
    } catch (MessagingException me) {
        throw new MailException(me);
    }

    if (_log.isDebugEnabled()) {
        stopWatch.stop();

        _log.debug("Downloaded " + jxMessages.length + " messages from folder " + jxFolder.getFullName()
                + " completed in " + stopWatch.getTime() + " ms");
    }
}

From source file:nz.net.orcon.kanban.automation.actions.EmailReceiverAction.java

public void generateMailNotification(String mailStoreProtocol, String mailStoreHost, String mailStoreUserName,
        String mailStorePassword, String notificationType, String fromFilter, String subjectFilter)
        throws Exception {
    Session session = getMailStoreSession(mailStoreProtocol, mailStoreHost, mailStoreUserName,
            mailStorePassword);/* w  w w . j av a 2 s  . c  o m*/
    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_WRITE);

        // check if fromFilter is specified
        List<String> fromFilterList = null;

        if (StringUtils.isNotBlank(fromFilter)) {
            String[] fromFilterArray = StringUtils.split(fromFilter, "|");
            fromFilterList = Arrays.asList(fromFilterArray);
        }

        // check if subjectFilter is specified
        List<String> subjectFilterList = null;
        if (StringUtils.isNotBlank(subjectFilter)) {
            String[] subjectFilterArray = StringUtils.split(subjectFilter, "|");
            subjectFilterList = Arrays.asList(subjectFilterArray);
        }
        Map<String, Object> context = new HashMap<String, Object>();
        // 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 address = fromAddress[0].toString();
            String from = extractFromAddress(address);
            if (StringUtils.isBlank(from)) {
                logger.warn("From Address is not proper " + from);
                return;
            }
            boolean isValidFrom = isValidMatch(fromFilterList, from);

            // filter based on fromFilter specified
            if (null == fromFilterList || isValidFrom) {
                String subject = msg.getSubject();

                boolean isValidSubject = isValidMatch(subjectFilterList, subject);
                if (null == subjectFilterList || isValidSubject) {
                    String toList = parseAddresses(msg.getRecipients(RecipientType.TO));
                    String ccList = parseAddresses(msg.getRecipients(RecipientType.CC));
                    String sentDate = msg.getSentDate().toString();

                    String messageContent = "";
                    try {
                        Object content = msg.getContent();
                        if (content != null) {
                            messageContent = content.toString();
                        }
                    } catch (Exception ex) {
                        messageContent = "[Error downloading content]";
                        ex.printStackTrace();
                    }
                    context.put("from", from);
                    context.put("to", toList);
                    context.put("cc", ccList);
                    context.put("subject", subject);
                    context.put("messagebody", messageContent);
                    context.put("sentdate", sentDate);

                    notificationController.createNotification(notificationType, context);
                    msg.setFlag(Flag.DELETED, true);
                } else {
                    logger.warn("subjectFilter doesn't match");
                }
            } else {
                logger.warn("this email originated from " + address
                        + " , which does not match fromAddress specified in the rule, it should be "
                        + fromFilter.toString());
            }
        }
        // disconnect and delete messages marked as DELETED
        folderInbox.close(true);
        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:com.jaeksoft.searchlib.crawler.mailbox.crawler.MailboxAbstractCrawler.java

final public void readMessage(IndexDocument crawlIndexDocument, IndexDocument parserIndexDocument,
        Folder folder, Message message, String id) throws Exception {

    crawlIndexDocument.addString(MailboxFieldEnum.message_id.name(), id);
    crawlIndexDocument.addString(MailboxFieldEnum.message_number.name(),
            Integer.toString(message.getMessageNumber()));
    if (message instanceof MimeMessage)
        crawlIndexDocument.addString(MailboxFieldEnum.content_id.name(),
                ((MimeMessage) message).getContentID());
    crawlIndexDocument.addString(MailboxFieldEnum.subject.name(), message.getSubject());
    putAddresses(crawlIndexDocument, message.getFrom(), MailboxFieldEnum.from_address.name(),
            MailboxFieldEnum.from_personal.name());
    putAddresses(crawlIndexDocument, message.getReplyTo(), MailboxFieldEnum.reply_to_address.name(),
            MailboxFieldEnum.reply_to_personal.name());
    putAddresses(crawlIndexDocument, message.getRecipients(RecipientType.TO),
            MailboxFieldEnum.recipient_to_address.name(), MailboxFieldEnum.recipient_to_personal.name());
    putAddresses(crawlIndexDocument, message.getRecipients(RecipientType.CC),
            MailboxFieldEnum.recipient_cc_address.name(), MailboxFieldEnum.recipient_cc_personal.name());
    putAddresses(crawlIndexDocument, message.getRecipients(RecipientType.BCC),
            MailboxFieldEnum.recipient_bcc_address.name(), MailboxFieldEnum.recipient_bcc_personal.name());
    Date dt = message.getSentDate();
    if (dt != null)
        crawlIndexDocument.addString(MailboxFieldEnum.send_date.name(), dt.toString());
    dt = message.getReceivedDate();/*www .j a  v  a  2 s.  c o  m*/
    if (dt != null)
        crawlIndexDocument.addString(MailboxFieldEnum.received_date.name(), dt.toString());
    if (message.isSet(Flag.ANSWERED))
        crawlIndexDocument.addString(MailboxFieldEnum.flags.name(), "ANSWERED");
    if (message.isSet(Flag.DELETED))
        crawlIndexDocument.addString(MailboxFieldEnum.flags.name(), "DELETED");
    if (message.isSet(Flag.DRAFT))
        crawlIndexDocument.addString(MailboxFieldEnum.flags.name(), "DRAFT");
    if (message.isSet(Flag.FLAGGED))
        crawlIndexDocument.addString(MailboxFieldEnum.flags.name(), "FLAGGED");
    if (message.isSet(Flag.SEEN))
        crawlIndexDocument.addString(MailboxFieldEnum.flags.name(), "SEEN");

    if (message instanceof MimeMessage) {
        MimeMessageParser mimeMessageParser = new MimeMessageParser((MimeMessage) message).parse();

        crawlIndexDocument.addString(MailboxFieldEnum.html_content.name(), mimeMessageParser.getHtmlContent());
        crawlIndexDocument.addString(MailboxFieldEnum.plain_content.name(),
                mimeMessageParser.getPlainContent());
        for (DataSource dataSource : mimeMessageParser.getAttachmentList()) {
            crawlIndexDocument.addString(MailboxFieldEnum.email_attachment_name.name(), dataSource.getName());
            crawlIndexDocument.addString(MailboxFieldEnum.email_attachment_type.name(),
                    dataSource.getContentType());
            if (parserSelector == null)
                continue;
            Parser attachParser = parserSelector.parseStream(null, dataSource.getName(),
                    dataSource.getContentType(), null, dataSource.getInputStream(), null, null, null);
            if (attachParser == null)
                continue;
            List<ParserResultItem> parserResults = attachParser.getParserResults();
            if (parserResults != null)
                for (ParserResultItem parserResult : parserResults)
                    crawlIndexDocument.addFieldIndexDocument(MailboxFieldEnum.email_attachment_content.name(),
                            parserResult.getParserDocument());
        }
    }
}

From source file:es.ucm.fdi.dalgs.mailbox.service.MailBoxService.java

/**
 * Returns new messages and fetches details for each message.
 *//*w  w w  . jav a 2  s.c o m*/
@Transactional(readOnly = false)
public ResultClass<Boolean> downloadEmails() {

    ResultClass<Boolean> result = new ResultClass<>();
    Properties properties = getServerProperties(protocol, host, port);
    Session session = Session.getDefaultInstance(properties);

    try {

        // connects to the message store
        Store store = session.getStore(protocol);

        store.connect(userName, password);
        // 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];

            String[] idHeaders = msg.getHeader("MESSAGE-ID");
            if (idHeaders != null && idHeaders.length > 0) {

                MessageBox exists = repositoryMailBox.getMessageBox(idHeaders[0]);
                if (exists == null) {

                    MessageBox messageBox = new MessageBox();
                    messageBox.setSubject(msg.getSubject());
                    messageBox.setCode(idHeaders[0]);

                    Address[] fromAddresses = msg.getFrom();
                    String from = InternetAddress.toString(fromAddresses);

                    if (from.startsWith("=?")) {
                        from = MimeUtility.decodeWord(from);
                    }
                    messageBox.setFrom(from);
                    String to = InternetAddress.toString(msg.getRecipients(RecipientType.TO));

                    if (to.startsWith("=?")) {
                        to = MimeUtility.decodeWord(to);
                    }
                    messageBox.setTo(to);

                    String[] replyHeaders = msg.getHeader("References");

                    if (replyHeaders != null && replyHeaders.length > 0) {
                        StringTokenizer tokens = new StringTokenizer(replyHeaders[0]);
                        MessageBox parent = repositoryMailBox.getMessageBox(tokens.nextToken());
                        if (parent != null)
                            parent.addReply(messageBox);
                    }

                    result = parseSubjectAndCreate(messageBox, msg);
                }
            }
        }

        folderInbox.close(false);
        store.close();

        return result;

    } catch (NoSuchProviderException ex) {
        logger.error("No provider for protocol: " + protocol);
        ex.printStackTrace();
    } catch (MessagingException ex) {
        logger.error("Could not connect to the message store");
        ex.printStackTrace();
    } catch (IOException e) {

        e.printStackTrace();
    }
    result.setSingleElement(false);
    return result;
}

From source file:com.aquest.emailmarketing.web.service.BouncedEmailService.java

/**
 * Process bounces./*from w ww  .  j  a  v  a2s .  c  om*/
 *
 * @param protocol the protocol
 * @param host the host
 * @param port the port
 * @param userName the user name
 * @param password the password
 */
public void processBounces(String protocol, String host, String port, String userName, String password) {
    Properties properties = getServerProperties(protocol, host, port);
    Session session = Session.getDefaultInstance(properties);

    List<BounceCode> bounceCodes = bounceCodeService.getAllBounceCodes();

    try {
        // connects to the message store
        Store store = session.getStore(protocol);
        System.out.println(userName);
        System.out.println(password);
        System.out.println(userName.length());
        System.out.println(password.length());
        //store.connect(userName, password);
        //TODO: ispraviti username i password da idu iz poziva a ne hardcoded
        store.connect("bojan.dimic@aquest-solutions.com", "bg181076");

        // 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++) {
            BouncedEmail bouncedEmail = new BouncedEmail();
            Message msg = messages[i];
            Address[] fromAddress = msg.getFrom();
            String from = fromAddress[0].toString();
            String failedAddress = "";
            Enumeration<?> headers = messages[i].getAllHeaders();
            while (headers.hasMoreElements()) {
                Header h = (Header) headers.nextElement();
                //System.out.println(h.getName() + ":" + h.getValue());
                //System.out.println("");                
                String mID = h.getName();
                if (mID.contains("X-Failed-Recipients")) {
                    failedAddress = h.getValue();
                }
            }
            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();
                }
            }

            String bounceReason = "Unknown reason";

            for (BounceCode bounceCode : bounceCodes) {
                if (messageContent.contains(bounceCode.getCode())) {
                    bounceReason = bounceCode.getExplanation();
                }
            }

            //                if(messageContent.contains(" 550 ") || messageContent.contains(" 550-")) {bounceReason="Users mailbox was unavailable (such as not found)";}
            //                if(messageContent.contains(" 554 ") || messageContent.contains(" 554-")) {bounceReason="The transaction failed for some unstated reason.";}
            //                
            //                // enhanced bounce codes
            //                if(messageContent.contains("5.0.0")) {bounceReason="Unknown issue";}
            //                if(messageContent.contains("5.1.0")) {bounceReason="Other address status";}
            //                if(messageContent.contains("5.1.1")) {bounceReason="Bad destination mailbox address";}
            //                if(messageContent.contains("5.1.2")) {bounceReason="Bad destination system address";}
            //                if(messageContent.contains("5.1.3")) {bounceReason="Bad destination mailbox address syntax";}
            //                if(messageContent.contains("5.1.4")) {bounceReason="Destination mailbox address ambiguous";}
            //                if(messageContent.contains("5.1.5")) {bounceReason="Destination mailbox address valid";}
            //                if(messageContent.contains("5.1.6")) {bounceReason="Mailbox has moved";}
            //                if(messageContent.contains("5.7.1")) {bounceReason="Delivery not authorized, message refused";}

            // 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 X-Failed-Recipients:" + failedAddress);
            System.out.println("\t Content Type:" + contentType);
            System.out.println("\t Bounce reason:" + bounceReason);
            //System.out.println("\t Message: " + messageContent);

            bouncedEmail.setEmail_address(failedAddress);
            bouncedEmail.setBounce_reason(bounceReason);

            //Date date = new Date();
            SimpleDateFormat formatter = new SimpleDateFormat("EEE MMM dd HH:mm:ss z yyyy", Locale.ENGLISH);
            SimpleDateFormat sqlFormat = new SimpleDateFormat("yyyy-mm-dd", Locale.ENGLISH);
            //String strDate = date.toString();
            System.out.println(sentDate);
            Date dt = null;
            //Date nd = null;
            try {
                dt = formatter.parse(sentDate);
                //nd = sqlFormat.parse(dt.toString());
            } catch (ParseException e) {
                e.printStackTrace();
            }
            System.out.println("Date " + dt.toString());
            //System.out.println("Date " + nd.toString());
            System.out.println(new Timestamp(new Date().getTime()));
            bouncedEmail.setSend_date(dt);
            bouncedEmailDao.saveOrUpdate(bouncedEmail);
        }

        // disconnect
        folderInbox.close(false);
        store.close();
    } catch (NoSuchProviderException ex) {
        System.out.println("No provider for protocol: " + protocol);
        ex.printStackTrace();
    } catch (MessagingException ex) {
        System.out.println("Could not connect to the message store");
        ex.printStackTrace();
    }
}

From source file:com.midori.confluence.plugin.mail2news.Mail2NewsJob.java

/**
 * Get the space key and subsequently the space from the recipient
 * email address.//from ww  w  .  j  ava2 s  .  c  om
 * 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);
}

From source file:com.cws.esolutions.core.utils.EmailUtils.java

/**
 * Processes and sends an email message as generated by the requesting
 * application. This method is utilized with a JNDI datasource.
 *
 * @param dataSource - The email message
 * @param authRequired - <code>true</code> if authentication is required, <code>false</code> otherwise
 * @param authList - If authRequired is true, this must be populated with the auth info
 * @return List - The list of email messages in the mailstore
 * @throws MessagingException {@link javax.mail.MessagingException} if an exception occurs during processing
 *///from   w ww.  j av a  2  s.co m
public static final synchronized List<EmailMessage> readEmailMessages(final Properties dataSource,
        final boolean authRequired, final List<String> authList) throws MessagingException {
    final String methodName = EmailUtils.CNAME
            + "#readEmailMessages(final Properties dataSource, final boolean authRequired, final List<String> authList) throws MessagingException";

    if (DEBUG) {
        DEBUGGER.debug(methodName);
        DEBUGGER.debug("dataSource: {}", dataSource);
        DEBUGGER.debug("authRequired: {}", authRequired);
        DEBUGGER.debug("authList: {}", authList);
    }

    Folder mailFolder = null;
    Session mailSession = null;
    Folder archiveFolder = null;
    List<EmailMessage> emailMessages = null;

    Calendar cal = Calendar.getInstance();
    cal.add(Calendar.HOUR, -24);

    final Long TIME_PERIOD = cal.getTimeInMillis();
    final URLName URL_NAME = (authRequired)
            ? new URLName(dataSource.getProperty("mailtype"), dataSource.getProperty("host"),
                    Integer.parseInt(dataSource.getProperty("port")), null, authList.get(0), authList.get(1))
            : new URLName(dataSource.getProperty("mailtype"), dataSource.getProperty("host"),
                    Integer.parseInt(dataSource.getProperty("port")), null, null, null);

    if (DEBUG) {
        DEBUGGER.debug("timePeriod: {}", TIME_PERIOD);
        DEBUGGER.debug("URL_NAME: {}", URL_NAME);
    }

    try {
        // Set up mail session
        mailSession = (authRequired) ? Session.getDefaultInstance(dataSource, new SMTPAuthenticator())
                : Session.getDefaultInstance(dataSource);

        if (DEBUG) {
            DEBUGGER.debug("mailSession: {}", mailSession);
        }

        if (mailSession == null) {
            throw new MessagingException("Unable to configure email services");
        }

        mailSession.setDebug(DEBUG);
        Store mailStore = mailSession.getStore(URL_NAME);
        mailStore.connect();

        if (DEBUG) {
            DEBUGGER.debug("mailStore: {}", mailStore);
        }

        if (!(mailStore.isConnected())) {
            throw new MessagingException("Failed to connect to mail service. Cannot continue.");
        }

        mailFolder = mailStore.getFolder("inbox");
        archiveFolder = mailStore.getFolder("archive");

        if (!(mailFolder.exists())) {
            throw new MessagingException("Requested folder does not exist. Cannot continue.");
        }

        mailFolder.open(Folder.READ_WRITE);

        if ((!(mailFolder.isOpen())) || (!(mailFolder.hasNewMessages()))) {
            throw new MessagingException("Failed to open requested folder. Cannot continue");
        }

        if (!(archiveFolder.exists())) {
            archiveFolder.create(Folder.HOLDS_MESSAGES);
        }

        Message[] mailMessages = mailFolder.getMessages();

        if (mailMessages.length == 0) {
            throw new MessagingException("No messages were found in the provided store.");
        }

        emailMessages = new ArrayList<EmailMessage>();

        for (Message message : mailMessages) {
            if (DEBUG) {
                DEBUGGER.debug("MailMessage: {}", message);
            }

            // validate the message here
            String messageId = message.getHeader("Message-ID")[0];
            Long messageDate = message.getReceivedDate().getTime();

            if (DEBUG) {
                DEBUGGER.debug("messageId: {}", messageId);
                DEBUGGER.debug("messageDate: {}", messageDate);
            }

            // only get emails for the last 24 hours
            // this should prevent us from pulling too
            // many emails
            if (messageDate >= TIME_PERIOD) {
                // process it
                Multipart attachment = (Multipart) message.getContent();
                Map<String, InputStream> attachmentList = new HashMap<String, InputStream>();

                for (int x = 0; x < attachment.getCount(); x++) {
                    BodyPart bodyPart = attachment.getBodyPart(x);

                    if (!(Part.ATTACHMENT.equalsIgnoreCase(bodyPart.getDisposition()))) {
                        continue;
                    }

                    attachmentList.put(bodyPart.getFileName(), bodyPart.getInputStream());
                }

                List<String> toList = new ArrayList<String>();
                List<String> ccList = new ArrayList<String>();
                List<String> bccList = new ArrayList<String>();
                List<String> fromList = new ArrayList<String>();

                for (Address from : message.getFrom()) {
                    fromList.add(from.toString());
                }

                if ((message.getRecipients(RecipientType.TO) != null)
                        && (message.getRecipients(RecipientType.TO).length != 0)) {
                    for (Address to : message.getRecipients(RecipientType.TO)) {
                        toList.add(to.toString());
                    }
                }

                if ((message.getRecipients(RecipientType.CC) != null)
                        && (message.getRecipients(RecipientType.CC).length != 0)) {
                    for (Address cc : message.getRecipients(RecipientType.CC)) {
                        ccList.add(cc.toString());
                    }
                }

                if ((message.getRecipients(RecipientType.BCC) != null)
                        && (message.getRecipients(RecipientType.BCC).length != 0)) {
                    for (Address bcc : message.getRecipients(RecipientType.BCC)) {
                        bccList.add(bcc.toString());
                    }
                }

                EmailMessage emailMessage = new EmailMessage();
                emailMessage.setMessageTo(toList);
                emailMessage.setMessageCC(ccList);
                emailMessage.setMessageBCC(bccList);
                emailMessage.setEmailAddr(fromList);
                emailMessage.setMessageAttachments(attachmentList);
                emailMessage.setMessageDate(message.getSentDate());
                emailMessage.setMessageSubject(message.getSubject());
                emailMessage.setMessageBody(message.getContent().toString());
                emailMessage.setMessageSources(message.getHeader("Received"));

                if (DEBUG) {
                    DEBUGGER.debug("emailMessage: {}", emailMessage);
                }

                emailMessages.add(emailMessage);

                if (DEBUG) {
                    DEBUGGER.debug("emailMessages: {}", emailMessages);
                }
            }

            // archive it
            archiveFolder.open(Folder.READ_WRITE);

            if (archiveFolder.isOpen()) {
                mailFolder.copyMessages(new Message[] { message }, archiveFolder);
                message.setFlag(Flags.Flag.DELETED, true);
            }
        }
    } catch (IOException iox) {
        throw new MessagingException(iox.getMessage(), iox);
    } catch (MessagingException mex) {
        throw new MessagingException(mex.getMessage(), mex);
    } finally {
        try {
            if ((mailFolder != null) && (mailFolder.isOpen())) {
                mailFolder.close(true);
            }

            if ((archiveFolder != null) && (archiveFolder.isOpen())) {
                archiveFolder.close(false);
            }
        } catch (MessagingException mx) {
            ERROR_RECORDER.error(mx.getMessage(), mx);
        }
    }

    return emailMessages;
}

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

/**
 * Convert Mime Message to Mail//www  . ja va2s. c  o  m
 */
public static Mail messageToMail(Message msg) throws MessagingException, IOException {
    com.openkm.bean.Mail mail = new com.openkm.bean.Mail();
    Calendar receivedDate = Calendar.getInstance();
    Calendar sentDate = Calendar.getInstance();

    // Can be void
    if (msg.getReceivedDate() != null) {
        receivedDate.setTime(msg.getReceivedDate());
    }

    // Can be void
    if (msg.getSentDate() != null) {
        sentDate.setTime(msg.getSentDate());
    }

    String body = getText(msg);

    // log.info("getText: "+body);
    if (body.charAt(0) == 'H') {
        mail.setMimeType(MimeTypeConfig.MIME_HTML);
    } else if (body.charAt(0) == 'T') {
        mail.setMimeType(MimeTypeConfig.MIME_TEXT);
    } else {
        mail.setMimeType(MimeTypeConfig.MIME_UNDEFINED);
    }

    if (msg.getFrom() != null && msg.getFrom().length > 0) {
        mail.setFrom(addressToString(msg.getFrom()[0]));
    }

    mail.setSize(msg.getSize());
    mail.setContent(body.substring(1));
    mail.setSubject((msg.getSubject() == null || msg.getSubject().isEmpty()) ? NO_SUBJECT : msg.getSubject());
    mail.setTo(addressToString(msg.getRecipients(Message.RecipientType.TO)));
    mail.setCc(addressToString(msg.getRecipients(Message.RecipientType.CC)));
    mail.setBcc(addressToString(msg.getRecipients(Message.RecipientType.BCC)));
    mail.setReceivedDate(receivedDate);
    mail.setSentDate(sentDate);

    return mail;
}

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. j  a va 2 s. co 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:de.saly.elasticsearch.support.IndexableMailMessage.java

public static IndexableMailMessage fromJavaMailMessage(final Message jmm, final boolean withTextContent,
        final boolean withAttachments, final boolean stripTags, List<String> headersToFields)
        throws MessagingException, IOException {
    final IndexableMailMessage im = new IndexableMailMessage();

    @SuppressWarnings("unchecked")
    final Enumeration<Header> allHeaders = jmm.getAllHeaders();

    final Set<IndexableHeader> headerList = new HashSet<IndexableHeader>();
    while (allHeaders.hasMoreElements()) {
        final Header h = allHeaders.nextElement();
        headerList.add(new IndexableHeader(h.getName(), h.getValue()));
    }//w  w  w. j a va 2s  .co m

    im.setHeaders(headerList.toArray(new IndexableHeader[headerList.size()]));

    im.setSelectedHeaders(extractHeaders(im.getHeaders(), headersToFields));

    if (jmm.getFolder() instanceof POP3Folder) {
        im.setPopId(((POP3Folder) jmm.getFolder()).getUID(jmm));
        im.setMailboxType("POP");

    } else {
        im.setMailboxType("IMAP");
    }

    if (jmm.getFolder() instanceof UIDFolder) {
        im.setUid(((UIDFolder) jmm.getFolder()).getUID(jmm));
    }

    im.setFolderFullName(jmm.getFolder().getFullName());

    im.setFolderUri(jmm.getFolder().getURLName().toString());

    im.setContentType(jmm.getContentType());
    im.setSubject(jmm.getSubject());
    im.setSize(jmm.getSize());
    im.setSentDate(jmm.getSentDate());

    if (jmm.getReceivedDate() != null) {
        im.setReceivedDate(jmm.getReceivedDate());
    }

    if (jmm.getFrom() != null && jmm.getFrom().length > 0) {
        im.setFrom(Address.fromJavaMailAddress(jmm.getFrom()[0]));
    }

    if (jmm.getRecipients(RecipientType.TO) != null) {
        im.setTo(Address.fromJavaMailAddress(jmm.getRecipients(RecipientType.TO)));
    }

    if (jmm.getRecipients(RecipientType.CC) != null) {
        im.setCc(Address.fromJavaMailAddress(jmm.getRecipients(RecipientType.CC)));
    }

    if (jmm.getRecipients(RecipientType.BCC) != null) {
        im.setBcc(Address.fromJavaMailAddress(jmm.getRecipients(RecipientType.BCC)));
    }

    if (withTextContent) {

        // try {

        String textContent = getText(jmm, 0);

        if (stripTags) {
            textContent = stripTags(textContent);
        }

        im.setTextContent(textContent);
        // } catch (final Exception e) {
        // logger.error("Unable to retrieve text content for message {} due to {}",
        // e, ((MimeMessage) jmm).getMessageID(), e);
        // }
    }

    if (withAttachments) {

        try {
            final Object content = jmm.getContent();

            // look for attachments
            if (jmm.isMimeType("multipart/*") && content instanceof Multipart) {
                List<ESAttachment> attachments = new ArrayList<ESAttachment>();

                final Multipart multipart = (Multipart) content;

                for (int i = 0; i < multipart.getCount(); i++) {
                    final BodyPart bodyPart = multipart.getBodyPart(i);
                    if (!Part.ATTACHMENT.equalsIgnoreCase(bodyPart.getDisposition())
                            && !StringUtils.isNotBlank(bodyPart.getFileName())) {
                        continue; // dealing with attachments only
                    }
                    final InputStream is = bodyPart.getInputStream();
                    final byte[] bytes = IOUtils.toByteArray(is);
                    IOUtils.closeQuietly(is);
                    attachments.add(new ESAttachment(bodyPart.getContentType(), bytes, bodyPart.getFileName()));
                }

                if (!attachments.isEmpty()) {
                    im.setAttachments(attachments.toArray(new ESAttachment[attachments.size()]));
                    im.setAttachmentCount(im.getAttachments().length);
                    attachments.clear();
                    attachments = null;
                }

            }
        } catch (final Exception e) {
            logger.error(
                    "Error indexing attachments (message will be indexed but without attachments) due to {}", e,
                    e.toString());
        }

    }

    im.setFlags(IMAPUtils.toStringArray(jmm.getFlags()));
    im.setFlaghashcode(jmm.getFlags().hashCode());

    return im;
}