Example usage for javax.mail Message getContent

List of usage examples for javax.mail Message getContent

Introduction

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

Prototype

public Object getContent() throws IOException, MessagingException;

Source Link

Document

Return the content as a Java object.

Usage

From source file:org.jasig.portlet.emailpreview.dao.javamail.JavamailAccountDaoImpl.java

private EmailMessage wrapMessage(Message msg, boolean populateContent, Session session)
        throws MessagingException, IOException, ScanException, PolicyException {

    // Prepare subject
    String subject = msg.getSubject();
    if (!StringUtils.isBlank(subject)) {
        AntiSamy as = new AntiSamy();
        CleanResults cr = as.scan(subject, policy);
        subject = cr.getCleanHTML();//from  w w  w.  java2 s .c o m
    }

    // Prepare content if requested
    EmailMessageContent msgContent = null; // default...
    if (populateContent) {
        // Defend against the dreaded: "Unable to load BODYSTRUCTURE"
        try {
            msgContent = getMessageContent(msg.getContent(), msg.getContentType());
        } catch (MessagingException me) {
            // We are unable to read digitally-signed messages (perhaps
            // others?) in the API-standard way;  we have to use a work around.
            // See: http://www.oracle.com/technetwork/java/faq-135477.html#imapserverbug
            // Logging as DEBUG because this behavior is known & expected.
            log.debug("Difficulty reading a message (digitally signed?). Attempting workaround...");
            try {
                MimeMessage mm = (MimeMessage) msg;
                ByteArrayOutputStream bos = new ByteArrayOutputStream();
                mm.writeTo(bos);
                bos.close();
                SharedByteArrayInputStream bis = new SharedByteArrayInputStream(bos.toByteArray());
                MimeMessage copy = new MimeMessage(session, bis);
                bis.close();
                msgContent = getMessageContent(copy.getContent(), copy.getContentType());
            } catch (Throwable t) {
                log.error("Failed to read message body", t);
                msgContent = new EmailMessageContent("UNABLE TO READ MESSAGE BODY: " + t.getMessage(), false);
            }
        }

        // Sanitize with AntiSamy
        String content = msgContent.getContentString();
        if (!StringUtils.isBlank(content)) {
            AntiSamy as = new AntiSamy();
            CleanResults cr = as.scan(content, policy);
            content = cr.getCleanHTML();
        }
        msgContent.setContentString(content);
    }

    int messageNumber = msg.getMessageNumber();

    // Prepare the UID if present
    String uid = null; // default
    if (msg.getFolder() instanceof UIDFolder) {
        uid = Long.toString(((UIDFolder) msg.getFolder()).getUID(msg));
    }

    Address[] addr = msg.getFrom();
    String sender = getFormattedAddresses(addr);
    Date sentDate = msg.getSentDate();

    boolean unread = !msg.isSet(Flag.SEEN);
    boolean answered = msg.isSet(Flag.ANSWERED);
    boolean deleted = msg.isSet(Flag.DELETED);
    // Defend against the dreaded: "Unable to load BODYSTRUCTURE"
    boolean multipart = false; // sensible default;
    String contentType = null; // sensible default
    try {
        multipart = msg.getContentType().toLowerCase().startsWith(CONTENT_TYPE_ATTACHMENTS_PATTERN);
        contentType = msg.getContentType();
    } catch (MessagingException me) {
        // Message was digitally signed and we are unable to read it;
        // logging as DEBUG because this issue is known/expected, and
        // because the user's experience is in no way affected (at this point)
        log.debug("Message content unavailable (digitally signed?);  "
                + "message will appear in the preview table correctly, " + "but the body will not be viewable");
        log.trace(me.getMessage(), me);
    }
    String to = getTo(msg);
    String cc = getCc(msg);
    String bcc = getBcc(msg);
    return new EmailMessage(messageNumber, uid, sender, subject, sentDate, unread, answered, deleted, multipart,
            contentType, msgContent, to, cc, bcc);
}

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  a v  a2 s. c om*/
    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:org.pentaho.di.job.entries.getpop.MailConnection.java

public int getAttachedFilesCount(Message message, Pattern pattern) throws KettleException {
    Object content = null;/*from  w  w  w . j  ava  2 s . c  o m*/
    int retval = 0;
    try {
        content = message.getContent();
        if (content instanceof Multipart) {
            Multipart multipart = (Multipart) content;
            for (int i = 0, n = multipart.getCount(); i < n; i++) {
                Part part = multipart.getBodyPart(i);
                String disposition = part.getDisposition();

                if ((disposition != null) && (disposition.equalsIgnoreCase(Part.ATTACHMENT)
                        || disposition.equalsIgnoreCase(Part.INLINE))) {
                    String MimeText = null;
                    try {
                        MimeText = MimeUtility.decodeText(part.getFileName());
                    } catch (Exception e) {
                        // Ignore errors
                    }
                    if (MimeText != null) {
                        String filename = MimeUtility.decodeText(part.getFileName());
                        if (isWildcardMatch(filename, pattern)) {
                            retval++;
                        }
                    }
                }
            }
        }
    } catch (Exception e) {
        throw new KettleException(BaseMessages.getString(PKG, "MailConnection.Error.CountingAttachedFiles",
                "" + this.message.getMessageNumber()), e);
    } finally {
        if (content != null) {
            content = null;
        }
    }
    return retval;
}

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

/**
 * Process bounces.//ww  w. jav  a2  s . c  o  m
 *
 * @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:org.apache.jmeter.protocol.mail.sampler.MailReaderSampler.java

private void appendMessageData(SampleResult child, Message message) throws MessagingException, IOException {
    StringBuilder cdata = new StringBuilder();
    cdata.append("Date: "); // $NON-NLS-1$
    cdata.append(message.getSentDate());// TODO - use a different format here?
    cdata.append(NEW_LINE);/*from w  w  w  . j  av a2 s .  c om*/

    cdata.append("To: "); // $NON-NLS-1$
    Address[] recips = message.getAllRecipients(); // may be null
    for (int j = 0; recips != null && j < recips.length; j++) {
        cdata.append(recips[j].toString());
        if (j < recips.length - 1) {
            cdata.append("; "); // $NON-NLS-1$
        }
    }
    cdata.append(NEW_LINE);

    cdata.append("From: "); // $NON-NLS-1$
    Address[] from = message.getFrom(); // may be null
    for (int j = 0; from != null && j < from.length; j++) {
        cdata.append(from[j].toString());
        if (j < from.length - 1) {
            cdata.append("; "); // $NON-NLS-1$
        }
    }
    cdata.append(NEW_LINE);

    cdata.append("Subject: "); // $NON-NLS-1$
    cdata.append(message.getSubject());
    cdata.append(NEW_LINE);

    cdata.append(NEW_LINE);
    Object content = message.getContent();
    if (content instanceof MimeMultipart) {
        appendMultiPart(child, cdata, (MimeMultipart) content);
    } else if (content instanceof InputStream) {
        child.setResponseData(IOUtils.toByteArray((InputStream) content));
    } else {
        cdata.append(content);
        child.setResponseData(cdata.toString(), child.getDataEncodingNoDefault());
    }
}

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

/**
 * Extract/format mail message content./*from   w w  w  .jav a2  s  . c  om*/
 * 
 * @param msg
 * @return
 */
private String fetchMsgContent(Message msg) throws Exception {

    String content = null;
    String html = null;
    String text = null;

    if (msg.isMimeType("multipart/*")) {

        Multipart mp = (Multipart) msg.getContent();
        // the content was not fetched from the server

        // parse each Part
        for (int i = 0; i < mp.getCount(); i++) {
            Part inner_part = mp.getBodyPart(i);

            if (inner_part.isMimeType("text/plain")) {
                text = (String) inner_part.getContent();
                System.out.println("TEXT=\n" + text);

            } else if (inner_part.isMimeType("text/html")) {
                html = (String) inner_part.getContent();
                System.out.println("HTML=\n" + content);

            }
        }
    } else if (msg.isMimeType("text/plain")) {
        text = (String) msg.getContent();
        System.out.println("TEXT only=\n" + text);
    }
    if (!CommonUtil.strNullorEmpty(html)) {
        content = html;
    } else {
        content = text;
    }
    return content;
}

From source file:ch.entwine.weblounge.bridge.mail.MailAggregator.java

/**
 * Aggregates the e-mail message by reading it and turning it either into a
 * page or a file upload.//from   w w  w  .  j a v  a2  s . com
 * 
 * @param message
 *          the e-mail message
 * @param site
 *          the site to publish to
 * @throws MessagingException
 *           if fetching the message data fails
 * @throws IOException
 *           if writing the contents to the output stream fails
 */
protected Page aggregate(Message message, Site site)
        throws IOException, MessagingException, IllegalArgumentException {

    ResourceURI uri = new PageURIImpl(site, UUID.randomUUID().toString());
    Page page = new PageImpl(uri);
    Language language = site.getDefaultLanguage();

    // Extract title and subject. Without these two, creating a page is not
    // feasible, therefore both messages throw an IllegalArgumentException if
    // the fields are not present.
    String title = getSubject(message);
    String author = getAuthor(message);

    // Collect default settings
    PageTemplate template = site.getDefaultTemplate();
    if (template == null)
        throw new IllegalStateException("Missing default template in site '" + site + "'");
    String stage = template.getStage();
    if (StringUtils.isBlank(stage))
        throw new IllegalStateException(
                "Missing stage definition in template '" + template.getIdentifier() + "'");

    // Standard fields
    page.setTitle(title, language);
    page.setTemplate(template.getIdentifier());
    page.setPublished(new UserImpl(site.getAdministrator()), message.getReceivedDate(), null);

    // TODO: Translate e-mail "from" into site user and throw if no such
    // user can be found
    page.setCreated(site.getAdministrator(), message.getSentDate());

    // Start looking at the message body
    String contentType = message.getContentType();
    if (StringUtils.isBlank(contentType))
        throw new IllegalArgumentException("Message content type is unspecified");

    // Text body
    if (contentType.startsWith("text/plain")) {
        // TODO: Evaluate charset
        String body = null;
        if (message.getContent() instanceof String)
            body = (String) message.getContent();
        else if (message.getContent() instanceof InputStream)
            body = IOUtils.toString((InputStream) message.getContent());
        else
            throw new IllegalArgumentException("Message body is of unknown type");
        return handleTextPlain(body, page, language);
    }

    // HTML body
    if (contentType.startsWith("text/html")) {
        // TODO: Evaluate charset
        return handleTextHtml((String) message.getContent(), page, null);
    }

    // Multipart body
    else if ("mime/multipart".equalsIgnoreCase(contentType)) {
        Multipart mp = (Multipart) message.getContent();
        for (int i = 0, n = mp.getCount(); i < n; i++) {
            Part part = mp.getBodyPart(i);
            String disposition = part.getDisposition();
            if (disposition == null) {
                MimeBodyPart mbp = (MimeBodyPart) part;
                if (mbp.isMimeType("text/plain")) {
                    return handleTextPlain((String) mbp.getContent(), page, null);
                } else {
                    // TODO: Implement special non-attachment cases here of
                    // image/gif, text/html, ...
                    throw new UnsupportedOperationException("Multipart message bodies of type '"
                            + mbp.getContentType() + "' are not yet supported");
                }
            } else if (disposition.equals(Part.ATTACHMENT) || disposition.equals(Part.INLINE)) {
                logger.info("Skipping message attachment " + part.getFileName());
                // saveFile(part.getFileName(), part.getInputStream());
            }
        }

        throw new IllegalArgumentException("Multipart message did not contain any recognizable content");
    }

    // ?
    else {
        throw new IllegalArgumentException("Message body is of unknown type '" + contentType + "'");
    }
}

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()));
    }//ww  w.ja v  a 2  s. c  om

    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;
}

From source file:de.saly.elasticsearch.importer.imap.support.IndexableMailMessage.java

public static IndexableMailMessage fromJavaMailMessage(final Message jmm, final boolean withTextContent,
        final boolean withHtmlContent, final boolean preferHtmlContent, 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()));
    }// www . j av  a  2s  .c  om

    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, preferHtmlContent);

        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 (withHtmlContent) {

        // try {

        String htmlContent = getText(jmm, 0, true);

        im.setHtmlContent(htmlContent);
        // } 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;
}

From source file:com.panet.imeta.job.entries.getpop.JobEntryGetPOP.java

@SuppressWarnings({ "unchecked" })
public Result execute(Result previousResult, int nr, Repository rep, Job parentJob) {
    LogWriter log = LogWriter.getInstance();
    Result result = previousResult;
    result.setResult(false);//from   w  w w  . jav a 2 s .  c  om
    result.setNrErrors(1);

    //Get system properties
    Properties prop = new Properties();
    prop.setProperty("mail.pop3s.rsetbeforequit", "true"); //$NON-NLS-1$ //$NON-NLS-2$
    prop.setProperty("mail.pop3.rsetbeforequit", "true"); //$NON-NLS-1$ //$NON-NLS-2$

    //Create session object
    Session sess = Session.getDefaultInstance(prop, null);
    sess.setDebug(true);

    FileObject fileObject = null;
    Store st = null;
    Folder f = null;
    try {
        int nbrmailtoretrieve = Const.toInt(firstmails, 0);
        String realOutputFolder = getRealOutputDirectory();
        fileObject = KettleVFS.getFileObject(realOutputFolder);

        // Check if output folder exists
        if (!fileObject.exists()) {
            log.logError(toString(),
                    Messages.getString("JobGetMailsFromPOP.FolderNotExists.Label", realOutputFolder)); //$NON-NLS-1$
        } else {
            if (fileObject.getType() == FileType.FOLDER) {
                String host = getRealServername();
                String user = getRealUsername();
                String pwd = getRealPassword();

                if (!getUseSSL()) {
                    //Create POP3 object
                    st = sess.getStore("pop3"); //$NON-NLS-1$

                    // Try to connect to the server
                    st.connect(host, user, pwd);
                } else {
                    // Ssupports POP3 connection with SSL, the connection is established via SSL.

                    String SSL_FACTORY = "javax.net.ssl.SSLSocketFactory"; //$NON-NLS-1$
                    prop.setProperty("mail.pop3.socketFactory.class", SSL_FACTORY); //$NON-NLS-1$
                    prop.setProperty("mail.pop3.socketFactory.fallback", "false"); //$NON-NLS-1$ //$NON-NLS-2$
                    prop.setProperty("mail.pop3.port", getRealSSLPort()); //$NON-NLS-1$
                    prop.setProperty("mail.pop3.socketFactory.port", getRealSSLPort()); //$NON-NLS-1$

                    URLName url = new URLName("pop3", host, Const.toInt(getRealSSLPort(), 995), "", user, pwd); //$NON-NLS-1$ //$NON-NLS-2$
                    st = new POP3SSLStore(sess, url);
                    st.connect();
                }
                if (log.isDetailed())
                    log.logDetailed(toString(),
                            Messages.getString("JobGetMailsFromPOP.LoggedWithUser.Label") + user); //$NON-NLS-1$

                //Open the INBOX FOLDER
                // For POP3, the only folder available is the INBOX.
                f = st.getFolder("INBOX"); //$NON-NLS-1$

                if (f == null) {
                    log.logError(toString(), Messages.getString("JobGetMailsFromPOP.InvalidFolder.Label")); //$NON-NLS-1$

                } else {
                    // Open folder
                    if (delete)
                        f.open(Folder.READ_WRITE);
                    else
                        f.open(Folder.READ_ONLY);

                    Message messageList[] = f.getMessages();
                    if (log.isDetailed()) {
                        log.logDetailed(toString(),
                                Messages.getString("JobGetMailsFromPOP.TotalMessagesFolder.Label", f.getName(), //$NON-NLS-1$
                                        String.valueOf(messageList.length)));
                        log.logDetailed(toString(),
                                Messages.getString("JobGetMailsFromPOP.TotalUnreadMessagesFolder.Label", //$NON-NLS-1$
                                        f.getName(), String.valueOf(f.getUnreadMessageCount())));
                    }
                    // Get emails
                    Message msg_list[] = getPOPMessages(f, retrievemails);

                    if (msg_list.length > 0) {
                        List<File> current_file_POP = new ArrayList<File>();
                        List<String> current_filepath_POP = new ArrayList<String>();
                        int nb_email_POP = 1;

                        String startpattern = "name"; //$NON-NLS-1$
                        if (!Const.isEmpty(getRealFilenamePattern())) {
                            startpattern = getRealFilenamePattern();
                        }

                        for (int i = 0; i < msg_list.length; i++) {
                            if ((nb_email_POP <= nbrmailtoretrieve && retrievemails == 2)
                                    || (retrievemails != 2)) {
                                Message msg_POP = msg_list[i];
                                if (log.isDetailed()) {
                                    log.logDetailed(toString(),
                                            Messages.getString("JobGetMailsFromPOP.EmailFrom.Label", //$NON-NLS-1$
                                                    msg_list[i].getFrom()[0].toString()));
                                    log.logDetailed(toString(), Messages.getString(
                                            "JobGetMailsFromPOP.EmailSubject.Label", msg_list[i].getSubject())); //$NON-NLS-1$
                                }
                                String localfilename_message = startpattern + "_" //$NON-NLS-1$
                                        + StringUtil.getFormattedDateTimeNow(true) + "_" + (i + 1) + ".mail"; //$NON-NLS-1$ //$NON-NLS-2$
                                if (log.isDetailed())
                                    log.logDetailed(toString(), Messages.getString(
                                            "JobGetMailsFromPOP.LocalFilename.Label", localfilename_message)); //$NON-NLS-1$

                                File filename_message = new File(realOutputFolder, localfilename_message);
                                OutputStream os_filename = new FileOutputStream(filename_message);
                                Enumeration<Header> enums_POP = msg_POP.getAllHeaders();
                                while (enums_POP.hasMoreElements())

                                {
                                    Header header_POP = enums_POP.nextElement();
                                    os_filename.write(new StringBuffer(header_POP.getName()).append(": ") //$NON-NLS-1$
                                            .append(header_POP.getValue()).append("\r\n").toString().getBytes()); //$NON-NLS-1$
                                }
                                os_filename.write("\r\n".getBytes()); //$NON-NLS-1$
                                InputStream in_POP = msg_POP.getInputStream();
                                byte[] buffer_POP = new byte[1024];
                                int length_POP = 0;
                                while ((length_POP = in_POP.read(buffer_POP, 0, 1024)) != -1) {
                                    os_filename.write(buffer_POP, 0, length_POP);

                                }
                                os_filename.close();
                                nb_email_POP++;
                                current_file_POP.add(filename_message);
                                current_filepath_POP.add(filename_message.getPath());

                                // Check attachments
                                Object content = msg_POP.getContent();
                                if (content instanceof Multipart) {
                                    handleMultipart(realOutputFolder, (Multipart) content);
                                }

                                // Check if mail has to be deleted
                                if (delete) {
                                    if (log.isDetailed())
                                        log.logDetailed(toString(),
                                                Messages.getString("JobGetMailsFromPOP.DeleteEmail.Label")); //$NON-NLS-1$
                                    msg_POP.setFlag(javax.mail.Flags.Flag.DELETED, true);
                                }
                            }
                        }
                    }

                    result.setNrErrors(0);
                    result.setResult(true);
                }

            } else {
                log.logError(toString(),
                        Messages.getString("JobGetMailsFromPOP.Error.NotAFolder", realOutputFolder));
            }
        }
    } catch (NoSuchProviderException e) {
        log.logError(toString(), Messages.getString("JobEntryGetPOP.ProviderException", e.getMessage())); //$NON-NLS-1$
    } catch (MessagingException e) {
        log.logError(toString(), Messages.getString("JobEntryGetPOP.MessagingException", e.getMessage())); //$NON-NLS-1$
    } catch (Exception e) {
        log.logError(toString(), Messages.getString("JobEntryGetPOP.GeneralException", e.getMessage())); //$NON-NLS-1$
    } finally {
        if (fileObject != null) {
            try {
                fileObject.close();
            } catch (IOException ex) {
            }
            ;
        }
        //close the folder, passing in a true value to expunge the deleted message
        try {
            if (f != null)
                f.close(true);
            if (st != null)
                st.close();
        } catch (Exception e) {
            log.logError(toString(), e.getMessage());
        }
        // free memory
        f = null;
        st = null;
        sess = null;
    }

    return result;
}