Example usage for javax.mail.internet MimeBodyPart isMimeType

List of usage examples for javax.mail.internet MimeBodyPart isMimeType

Introduction

In this page you can find the example usage for javax.mail.internet MimeBodyPart isMimeType.

Prototype

@Override
public boolean isMimeType(String mimeType) throws MessagingException 

Source Link

Document

Is this Part of the specified MIME type?

Usage

From source file:com.ctriposs.r2.message.rest.QueryTunnelUtil.java

/**
 * Takes a Request object that has been encoded for tunnelling as a POST with an X-HTTP-Override-Method header and
 * creates a new request that represents the intended original request
 *
 * @param request the request to be decoded
 *
 * @return a decoded RestRequest/*from w w  w  .  j  a  v  a 2s . co m*/
 */
public static RestRequest decode(final RestRequest request)
        throws MessagingException, IOException, URISyntaxException {
    if (request.getHeader(HEADER_METHOD_OVERRIDE) == null) {
        // Not a tunnelled request, just pass thru
        return request;
    }

    String query = null;
    byte[] entity = new byte[0];

    // All encoded requests must have a content type. If the header is missing, ContentType throws an exception
    ContentType contentType = new ContentType(request.getHeader(HEADER_CONTENT_TYPE));

    RestRequestBuilder requestBuilder = request.builder();

    // Get copy of headers and remove the override
    Map<String, String> h = new HashMap<String, String>(request.getHeaders());
    h.remove(HEADER_METHOD_OVERRIDE);

    // Simple case, just extract query params from entity, append to query, and clear entity
    if (contentType.getBaseType().equals(FORM_URL_ENCODED)) {
        query = request.getEntity().asString(Data.UTF_8_CHARSET);
        h.remove(HEADER_CONTENT_TYPE);
        h.remove(CONTENT_LENGTH);
    } else if (contentType.getBaseType().equals(MULTIPART)) {
        // Clear these in case there is no body part
        h.remove(HEADER_CONTENT_TYPE);
        h.remove(CONTENT_LENGTH);

        MimeMultipart multi = new MimeMultipart(new DataSource() {
            @Override
            public InputStream getInputStream() throws IOException {
                return request.getEntity().asInputStream();
            }

            @Override
            public OutputStream getOutputStream() throws IOException {
                return null;
            }

            @Override
            public String getContentType() {
                return request.getHeader(HEADER_CONTENT_TYPE);
            }

            @Override
            public String getName() {
                return null;
            }
        });

        for (int i = 0; i < multi.getCount(); i++) {
            MimeBodyPart part = (MimeBodyPart) multi.getBodyPart(i);

            if (part.isMimeType(FORM_URL_ENCODED) && query == null) {
                // Assume the first segment we come to that is urlencoded is the tunneled query params
                query = IOUtils.toString((InputStream) part.getContent(), UTF8);
            } else if (entity.length <= 0) {
                // Assume the first non-urlencoded content we come to is the intended entity.
                entity = IOUtils.toByteArray((InputStream) part.getContent());
                h.put(CONTENT_LENGTH, Integer.toString(entity.length));
                h.put(HEADER_CONTENT_TYPE, part.getContentType());
            } else {
                // If it's not form-urlencoded and we've already found another section,
                // this has to be be an extra body section, which we have no way to handle.
                // Proceed with the request as if the 1st part we found was the expected body,
                // but log a warning in case some client is constructing a request that doesn't
                // follow the rules.
                String unexpectedContentType = part.getContentType();
                LOG.warn("Unexpected body part in X-HTTP-Method-Override request, type="
                        + unexpectedContentType);
            }
        }
    }

    // Based on what we've found, construct the modified request. It's possible that someone has
    // modified the request URI, adding extra query params for debugging, tracking, etc, so
    // we have to check and append the original query correctly.
    if (query != null && query.length() > 0) {
        String separator = "&";
        String existingQuery = request.getURI().getRawQuery();

        if (existingQuery == null) {
            separator = "?";
        } else if (existingQuery.isEmpty()) {
            // This would mean someone has appended a "?" with no args to the url underneath us
            separator = "";
        }

        requestBuilder.setURI(new URI(request.getURI().toString() + separator + query));
    }
    requestBuilder.setEntity(entity);
    requestBuilder.setHeaders(h);
    requestBuilder.setMethod(request.getHeader(HEADER_METHOD_OVERRIDE));

    return requestBuilder.build();
}

From source file:com.linkedin.r2.message.rest.QueryTunnelUtil.java

/**
 * Takes a Request object that has been encoded for tunnelling as a POST with an X-HTTP-Override-Method header and
 * creates a new request that represents the intended original request
 *
 * @param request the request to be decoded
 * @param requestContext a RequestContext object associated with the request
 *
 * @return a decoded RestRequest/* ww w .  ja v a2 s .c  om*/
 */
public static RestRequest decode(final RestRequest request, RequestContext requestContext)
        throws MessagingException, IOException, URISyntaxException {
    if (request.getHeader(HEADER_METHOD_OVERRIDE) == null) {
        // Not a tunnelled request, just pass thru
        return request;
    }

    String query = null;
    byte[] entity = new byte[0];

    // All encoded requests must have a content type. If the header is missing, ContentType throws an exception
    ContentType contentType = new ContentType(request.getHeader(HEADER_CONTENT_TYPE));

    RestRequestBuilder requestBuilder = request.builder();

    // Get copy of headers and remove the override
    Map<String, String> h = new HashMap<String, String>(request.getHeaders());
    h.remove(HEADER_METHOD_OVERRIDE);

    // Simple case, just extract query params from entity, append to query, and clear entity
    if (contentType.getBaseType().equals(FORM_URL_ENCODED)) {
        query = request.getEntity().asString(Data.UTF_8_CHARSET);
        h.remove(HEADER_CONTENT_TYPE);
        h.remove(CONTENT_LENGTH);
    } else if (contentType.getBaseType().equals(MULTIPART)) {
        // Clear these in case there is no body part
        h.remove(HEADER_CONTENT_TYPE);
        h.remove(CONTENT_LENGTH);

        MimeMultipart multi = new MimeMultipart(new DataSource() {
            @Override
            public InputStream getInputStream() throws IOException {
                return request.getEntity().asInputStream();
            }

            @Override
            public OutputStream getOutputStream() throws IOException {
                return null;
            }

            @Override
            public String getContentType() {
                return request.getHeader(HEADER_CONTENT_TYPE);
            }

            @Override
            public String getName() {
                return null;
            }
        });

        for (int i = 0; i < multi.getCount(); i++) {
            MimeBodyPart part = (MimeBodyPart) multi.getBodyPart(i);

            if (part.isMimeType(FORM_URL_ENCODED) && query == null) {
                // Assume the first segment we come to that is urlencoded is the tunneled query params
                query = IOUtils.toString((InputStream) part.getContent(), UTF8);
            } else if (entity.length <= 0) {
                // Assume the first non-urlencoded content we come to is the intended entity.
                Object content = part.getContent();
                if (content instanceof MimeMultipart) {
                    ByteArrayOutputStream os = new ByteArrayOutputStream();
                    ((MimeMultipart) content).writeTo(os);
                    entity = os.toByteArray();
                } else {
                    entity = IOUtils.toByteArray((InputStream) content);
                }
                h.put(CONTENT_LENGTH, Integer.toString(entity.length));
                h.put(HEADER_CONTENT_TYPE, part.getContentType());
            } else {
                // If it's not form-urlencoded and we've already found another section,
                // this has to be be an extra body section, which we have no way to handle.
                // Proceed with the request as if the 1st part we found was the expected body,
                // but log a warning in case some client is constructing a request that doesn't
                // follow the rules.
                String unexpectedContentType = part.getContentType();
                LOG.warn("Unexpected body part in X-HTTP-Method-Override request, type="
                        + unexpectedContentType);
            }
        }
    }

    // Based on what we've found, construct the modified request. It's possible that someone has
    // modified the request URI, adding extra query params for debugging, tracking, etc, so
    // we have to check and append the original query correctly.
    if (query != null && query.length() > 0) {
        String separator = "&";
        String existingQuery = request.getURI().getRawQuery();

        if (existingQuery == null) {
            separator = "?";
        } else if (existingQuery.isEmpty()) {
            // This would mean someone has appended a "?" with no args to the url underneath us
            separator = "";
        }

        requestBuilder.setURI(new URI(request.getURI().toString() + separator + query));
    }
    requestBuilder.setEntity(entity);
    requestBuilder.setHeaders(h);
    requestBuilder.setMethod(request.getHeader(HEADER_METHOD_OVERRIDE));

    requestContext.putLocalAttr(R2Constants.IS_QUERY_TUNNELED, true);

    return requestBuilder.build();
}

From source file:ca.airspeed.demo.testingemail.EmailServiceTest.java

@Test
public void testWithAttachment() throws Exception {
    // Given://from w  ww . j  a  va  2  s .com
    EmailService service = makeALocalMailer();

    InternetAddress expectedTo = new InternetAddress("Indiana.Jones@domain.com", "Indiana Jones");
    String expectedSubject = "This is a Test Email";
    String expectedTextBody = "This is a test with a PDF attachment.";
    List<FileSystemResource> filesToAttach = new ArrayList<FileSystemResource>();
    filesToAttach.add(
            new FileSystemResource(this.getClass().getClassLoader().getResource("HelloWorld.pdf").getFile()));

    // When:
    service.sendWithAttachments(expectedTo, expectedSubject, expectedTextBody, filesToAttach);

    // Then:
    List<WiserMessage> messages = wiser.getMessages();
    assertEquals("Number of messages sent;", 1, messages.size());
    WiserMessage message = messages.get(0);
    MimeMessage mimeMessage = message.getMimeMessage();

    assertEquals("Subject;", expectedSubject, mimeMessage.getSubject());

    MimeMultipart body = ((MimeMultipart) mimeMessage.getContent());
    assertEquals("Number of MIME Parts in the body;", 2, body.getCount());

    MimeBodyPart attachment = ((MimeBodyPart) body.getBodyPart(1));
    assertTrue("Attachment MIME Type should be application/pdf", attachment.isMimeType("application/pdf"));
    assertEquals("Attachment filename;", "HelloWorld.pdf", attachment.getFileName());
    assertTrue("No content found in the attachment.", isNotBlank(attachment.getContent().toString()));
}

From source file:ca.airspeed.demo.testingemail.EmailServiceTest.java

/**
 * When we send out an email with just a text body, et expect to get a
 * Multipart email having only a plain text body.
 *///from www.  ja  v a  2  s . c om
@Test
public void testSimpleEmail() throws Exception {
    // Given:
    EmailService service = makeALocalMailer();

    InternetAddress expectedTo = new InternetAddress("Indiana.Jones@domain.com", "Indiana Jones");
    String expectedSubject = "This is a Test Email";
    String expectedTextBody = "This is a simple test.";

    // When:
    service.sendSimpleEmail(expectedTo, expectedSubject, expectedTextBody);

    // Then:
    List<WiserMessage> messages = wiser.getMessages();
    assertEquals("Number of messages sent;", 1, messages.size());

    WiserMessage message = messages.get(0);
    assertNotNull("No message was actually sent.", message);
    MimeMessage mimeMessage = message.getMimeMessage();
    Address[] toRecipients = mimeMessage.getRecipients(RecipientType.TO);
    assertEquals("Number of To: Recipient;", 1, toRecipients.length);
    Address toRecipient = toRecipients[0];
    assertEquals("To: Recipient;", expectedTo, toRecipient);

    InternetAddress expectedFrom = new InternetAddress("admin@domain.com", "Domain Admin");
    Address[] fromArr = mimeMessage.getFrom();
    assertEquals("From: email addresses;", 1, fromArr.length);
    assertEquals("Email From: address,", expectedFrom, fromArr[0]);

    assertEquals("Subject;", expectedSubject, mimeMessage.getSubject());

    assertNotNull("The date of the email cannot be null.", mimeMessage.getSentDate());

    MimeMultipart body = ((MimeMultipart) mimeMessage.getContent());
    assertEquals("Number of MIME Parts in the body;", 1, body.getCount());
    MimeMultipart textPart = ((MimeMultipart) body.getBodyPart(0).getContent());
    assertEquals("Number of MIME parts in the text body;", 1, textPart.getCount());
    MimeBodyPart plainTextPart = ((MimeBodyPart) textPart.getBodyPart(0));
    assertTrue("Expected the plain text content to be text/plain.", plainTextPart.isMimeType("text/plain"));
    assertEquals("Text Body;", expectedTextBody, plainTextPart.getContent());
}

From source file:ru.retbansk.utils.scheduled.impl.ReadEmailAndConvertToXmlSpringImpl.java

/**
 * Loads email properties, reads email messages, 
 * converts their multipart bodies into string,
 * send error emails if message doesn't contain valid report and at last returns a reversed Set of the Valid Reports
 * <p><b> deletes messages/*from w w  w.  ja va 2s. c  om*/
 * @see #readEmail()
 * @see #convertToXml(HashSet)
 * @see ru.retbansk.utils.scheduled.ReplyManager
 * @return HashSet<DayReport> of the Valid Day Reports
 */
@Override
public HashSet<DayReport> readEmail() throws Exception {

    Properties prop = loadProperties();
    String host = prop.getProperty("host");
    String user = prop.getProperty("user");
    String password = prop.getProperty("password");
    path = prop.getProperty("path");

    // Get system properties
    Properties properties = System.getProperties();

    // Get the default Session object.
    Session session = Session.getDefaultInstance(properties);

    // Get a Store object that implements the specified protocol.
    Store store = session.getStore("pop3");

    // Connect to the current host using the specified username and
    // password.
    store.connect(host, user, password);

    // Create a Folder object corresponding to the given name.
    Folder folder = store.getFolder("inbox");

    // Open the Folder.
    folder.open(Folder.READ_WRITE);
    HashSet<DayReport> dayReportSet = new HashSet<DayReport>();
    try {

        // Getting messages from the folder
        Message[] message = folder.getMessages();
        // Reversing the order in the array with the use of Set to make the last one final
        Collections.reverse(Arrays.asList(message));

        // Reading messages.
        String body;
        for (int i = 0; i < message.length; i++) {
            DayReport dayReport = null;
            dayReport = new DayReport();
            dayReport.setPersonId(((InternetAddress) message[i].getFrom()[0]).getAddress());
            Calendar calendar = Calendar.getInstance(TimeZone.getTimeZone("GMT+3"));
            calendar.setTime(message[i].getSentDate());
            dayReport.setCalendar(calendar);
            dayReport.setSubject(message[i].getSubject());
            List<TaskReport> reportList = null;

            //Release the string from email message body
            body = "";
            Object content = message[i].getContent();
            if (content instanceof java.lang.String) {
                body = (String) content;
            } else if (content instanceof Multipart) {
                Multipart mp = (Multipart) content;

                for (int j = 0; j < mp.getCount(); j++) {
                    Part part = mp.getBodyPart(j);

                    String disposition = part.getDisposition();

                    if (disposition == null) {
                        MimeBodyPart mbp = (MimeBodyPart) part;
                        if (mbp.isMimeType("text/plain")) {
                            body += (String) mbp.getContent();
                        }
                    } else if ((disposition != null)
                            && (disposition.equals(Part.ATTACHMENT) || disposition.equals(Part.INLINE))) {
                        MimeBodyPart mbp = (MimeBodyPart) part;
                        if (mbp.isMimeType("text/plain")) {
                            body += (String) mbp.getContent();
                        }
                    }
                }
            }

            //Put the string (body of email message) and get list of valid reports else send error
            reportList = new ArrayList<TaskReport>();
            reportList = giveValidReports(body, message[i].getSentDate());
            //Check for valid day report. To be valid it should have size of reportList > 0.
            if (reportList.size() > 0) {
                // adding valid ones to Set
                dayReport.setReportList(reportList);
                dayReportSet.add(dayReport);
            } else {
                // This message doesn't have valid reports. Sending an error reply.
                logger.info("Invalid Day Report detected. Sending an error reply");
                ReplyManager man = new ReplyManagerSimpleImpl();
                man.sendError(dayReport);
            }
            // Delete message
            message[i].setFlag(Flags.Flag.DELETED, true);
        }

    } finally {
        // true tells the mail server to expunge deleted messages.
        folder.close(true);
        store.close();
    }

    return dayReportSet;
}

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./*w w  w .  j  av a 2 s.  co  m*/
 * 
 * @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:org.apache.manifoldcf.crawler.connectors.email.EmailConnector.java

/** Process a set of documents.
* This is the method that should cause each document to be fetched, processed, and the results either added
* to the queue of documents for the current job, and/or entered into the incremental ingestion manager.
* The document specification allows this class to filter what is done based on the job.
* The connector will be connected before this method can be called.
*@param documentIdentifiers is the set of document identifiers to process.
*@param statuses are the currently-stored document versions for each document in the set of document identifiers
* passed in above.//from w  ww  . j a  va2s. com
*@param activities is the interface this method should use to queue up new document references
* and ingest documents.
*@param jobMode is an integer describing how the job is being run, whether continuous or once-only.
*@param usesDefaultAuthority will be true only if the authority in use for these documents is the default one.
*/
@Override
public void processDocuments(String[] documentIdentifiers, IExistingVersions statuses, Specification spec,
        IProcessActivity activities, int jobMode, boolean usesDefaultAuthority)
        throws ManifoldCFException, ServiceInterruption {

    List<String> requiredMetadata = new ArrayList<String>();
    for (int i = 0; i < spec.getChildCount(); i++) {
        SpecificationNode sn = spec.getChild(i);
        if (sn.getType().equals(EmailConfig.NODE_METADATA)) {
            String metadataAttribute = sn.getAttributeValue(EmailConfig.ATTRIBUTE_NAME);
            requiredMetadata.add(metadataAttribute);
        }
    }

    // Keep a cached set of open folders
    Map<String, Folder> openFolders = new HashMap<String, Folder>();
    try {

        for (String documentIdentifier : documentIdentifiers) {
            String versionString = "_" + urlTemplate; // NOT empty; we need to make ManifoldCF understand that this is a document that never will change.

            // Check if we need to index
            if (!activities.checkDocumentNeedsReindexing(documentIdentifier, versionString))
                continue;

            String compositeID = documentIdentifier;
            String version = versionString;
            String folderName = extractFolderNameFromDocumentIdentifier(compositeID);
            String id = extractEmailIDFromDocumentIdentifier(compositeID);

            String errorCode = null;
            String errorDesc = null;
            Long fileLengthLong = null;
            long startTime = System.currentTimeMillis();
            try {
                try {
                    Folder folder = openFolders.get(folderName);
                    if (folder == null) {
                        getSession();
                        OpenFolderThread oft = new OpenFolderThread(session, folderName);
                        oft.start();
                        folder = oft.finishUp();
                        openFolders.put(folderName, folder);
                    }

                    if (Logging.connectors.isDebugEnabled())
                        Logging.connectors.debug("Email: Processing document identifier '" + compositeID + "'");
                    SearchTerm messageIDTerm = new MessageIDTerm(id);

                    getSession();
                    SearchMessagesThread smt = new SearchMessagesThread(session, folder, messageIDTerm);
                    smt.start();
                    Message[] message = smt.finishUp();

                    String msgURL = makeDocumentURI(urlTemplate, folderName, id);

                    Message msg = null;
                    for (Message msg2 : message) {
                        msg = msg2;
                    }
                    if (msg == null) {
                        // email was not found
                        activities.deleteDocument(id);
                        continue;
                    }

                    if (!activities.checkURLIndexable(msgURL)) {
                        errorCode = activities.EXCLUDED_URL;
                        errorDesc = "Excluded because of URL ('" + msgURL + "')";
                        activities.noDocument(id, version);
                        continue;
                    }

                    long fileLength = msg.getSize();
                    if (!activities.checkLengthIndexable(fileLength)) {
                        errorCode = activities.EXCLUDED_LENGTH;
                        errorDesc = "Excluded because of length (" + fileLength + ")";
                        activities.noDocument(id, version);
                        continue;
                    }

                    Date sentDate = msg.getSentDate();
                    if (!activities.checkDateIndexable(sentDate)) {
                        errorCode = activities.EXCLUDED_DATE;
                        errorDesc = "Excluded because of date (" + sentDate + ")";
                        activities.noDocument(id, version);
                        continue;
                    }

                    String mimeType = "text/plain";
                    if (!activities.checkMimeTypeIndexable(mimeType)) {
                        errorCode = activities.EXCLUDED_DATE;
                        errorDesc = "Excluded because of mime type ('" + mimeType + "')";
                        activities.noDocument(id, version);
                        continue;
                    }

                    RepositoryDocument rd = new RepositoryDocument();
                    rd.setFileName(msg.getFileName());
                    rd.setMimeType(mimeType);
                    rd.setCreatedDate(sentDate);
                    rd.setModifiedDate(sentDate);

                    String subject = StringUtils.EMPTY;
                    for (String metadata : requiredMetadata) {
                        if (metadata.toLowerCase().equals(EmailConfig.EMAIL_TO)) {
                            Address[] to = msg.getRecipients(Message.RecipientType.TO);
                            String[] toStr = new String[to.length];
                            int j = 0;
                            for (Address address : to) {
                                toStr[j] = address.toString();
                            }
                            rd.addField(EmailConfig.EMAIL_TO, toStr);
                        } else if (metadata.toLowerCase().equals(EmailConfig.EMAIL_FROM)) {
                            Address[] from = msg.getFrom();
                            String[] fromStr = new String[from.length];
                            int j = 0;
                            for (Address address : from) {
                                fromStr[j] = address.toString();
                            }
                            rd.addField(EmailConfig.EMAIL_TO, fromStr);

                        } else if (metadata.toLowerCase().equals(EmailConfig.EMAIL_SUBJECT)) {
                            subject = msg.getSubject();
                            rd.addField(EmailConfig.EMAIL_SUBJECT, subject);
                        } else if (metadata.toLowerCase().equals(EmailConfig.EMAIL_BODY)) {
                            Multipart mp = (Multipart) msg.getContent();
                            for (int k = 0, n = mp.getCount(); k < n; k++) {
                                Part part = mp.getBodyPart(k);
                                String disposition = part.getDisposition();
                                if ((disposition == null)) {
                                    MimeBodyPart mbp = (MimeBodyPart) part;
                                    if (mbp.isMimeType(EmailConfig.MIMETYPE_TEXT_PLAIN)) {
                                        rd.addField(EmailConfig.EMAIL_BODY, mbp.getContent().toString());
                                    } else if (mbp.isMimeType(EmailConfig.MIMETYPE_HTML)) {
                                        rd.addField(EmailConfig.EMAIL_BODY, mbp.getContent().toString()); //handle html accordingly. Returns content with html tags
                                    }
                                }
                            }
                        } else if (metadata.toLowerCase().equals(EmailConfig.EMAIL_DATE)) {
                            rd.addField(EmailConfig.EMAIL_DATE, sentDate.toString());
                        } else if (metadata.toLowerCase().equals(EmailConfig.EMAIL_ATTACHMENT_ENCODING)) {
                            Multipart mp = (Multipart) msg.getContent();
                            if (mp != null) {
                                String[] encoding = new String[mp.getCount()];
                                for (int k = 0, n = mp.getCount(); k < n; k++) {
                                    Part part = mp.getBodyPart(k);
                                    String disposition = part.getDisposition();
                                    if ((disposition != null) && ((disposition.equals(Part.ATTACHMENT)
                                            || (disposition.equals(Part.INLINE))))) {
                                        encoding[k] = part.getFileName().split("\\?")[1];

                                    }
                                }
                                rd.addField(EmailConfig.ENCODING_FIELD, encoding);
                            }
                        } else if (metadata.toLowerCase().equals(EmailConfig.EMAIL_ATTACHMENT_MIMETYPE)) {
                            Multipart mp = (Multipart) msg.getContent();
                            String[] MIMEType = new String[mp.getCount()];
                            for (int k = 0, n = mp.getCount(); k < n; k++) {
                                Part part = mp.getBodyPart(k);
                                String disposition = part.getDisposition();
                                if ((disposition != null) && ((disposition.equals(Part.ATTACHMENT)
                                        || (disposition.equals(Part.INLINE))))) {
                                    MIMEType[k] = part.getContentType();

                                }
                            }
                            rd.addField(EmailConfig.MIMETYPE_FIELD, MIMEType);
                        }
                    }

                    InputStream is = msg.getInputStream();
                    try {
                        rd.setBinary(is, fileLength);
                        activities.ingestDocumentWithException(id, version, msgURL, rd);
                        errorCode = "OK";
                        fileLengthLong = new Long(fileLength);
                    } finally {
                        is.close();
                    }
                } catch (InterruptedException e) {
                    throw new ManifoldCFException(e.getMessage(), ManifoldCFException.INTERRUPTED);
                } catch (MessagingException e) {
                    errorCode = e.getClass().getSimpleName().toUpperCase(Locale.ROOT);
                    errorDesc = e.getMessage();
                    handleMessagingException(e, "processing email");
                } catch (IOException e) {
                    errorCode = e.getClass().getSimpleName().toUpperCase(Locale.ROOT);
                    errorDesc = e.getMessage();
                    handleIOException(e, "processing email");
                    throw new ManifoldCFException(e.getMessage(), e);
                }
            } catch (ManifoldCFException e) {
                if (e.getErrorCode() == ManifoldCFException.INTERRUPTED)
                    errorCode = null;
                throw e;
            } finally {
                if (errorCode != null)
                    activities.recordActivity(new Long(startTime), EmailConfig.ACTIVITY_FETCH, fileLengthLong,
                            documentIdentifier, errorCode, errorDesc, null);
            }
        }
    } finally {
        for (Folder f : openFolders.values()) {
            try {
                CloseFolderThread cft = new CloseFolderThread(session, f);
                cft.start();
                cft.finishUp();
            } catch (InterruptedException e) {
                throw new ManifoldCFException(e.getMessage(), ManifoldCFException.INTERRUPTED);
            } catch (MessagingException e) {
                handleMessagingException(e, "closing folders");
            }
        }
    }

}

From source file:org.campware.cream.modules.scheduledjobs.Pop3Job.java

private String handleAlternative(Object o, String content) throws Exception {

    Multipart multipart = (Multipart) o;
    for (int k = 0, n = multipart.getCount(); k < n; k++) {
        Part part = multipart.getBodyPart(k);
        MimeBodyPart mbp = (MimeBodyPart) part;

        if (mbp.isMimeType("text/html")) {
            log.debug("---------------> Handle html alternative. ");
            content += (String) part.getContent();
        }/*from  w w w . j  a  v a  2s.com*/

    }

    return content;
}

From source file:org.campware.cream.modules.scheduledjobs.Pop3Job.java

private String handleMulitipart(Object o, String content, InboxEvent inboxentry) throws Exception {

    Multipart multipart = (Multipart) o;

    for (int k = 0, n = multipart.getCount(); k < n; k++) {

        Part part = multipart.getBodyPart(k);
        String disposition = part.getDisposition();
        MimeBodyPart mbp = (MimeBodyPart) part;

        if ((disposition != null) && (disposition.equals(Part.ATTACHMENT))) {
            log.debug("---------------> Saving File " + part.getFileName() + " " + part.getContent());
            saveAttachment(part, inboxentry);

        } else {//from  ww w.  j  a v a 2s.  c o  m
            // Check if plain
            if (mbp.isMimeType("text/plain")) {
                log.debug("---------------> Handle plain. ");
                content += "<PRE style=\"font-size: 12px;\">" + (String) part.getContent() + "</PRE>";
                // Check if html
            } else if (mbp.isMimeType("text/html")) {
                log.debug("---------------> Handle plain. ");
                content += (String) part.getContent();
            } else {
                // Special non-attachment cases here of
                // image/gif, text/html, ...
                log.debug("---------------> Special non-attachment cases " + " " + part.getContentType());
                if (mbp.isMimeType("multipart/*")) {
                    Object ob = part.getContent();
                    content = this.handleMulitipart(ob, content, inboxentry) + "\n\n" + content;
                } else {
                    saveAttachment(part, inboxentry);
                }
            }
        }
    }

    return content;
}

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

/**
 *
 * @param pop3Host/* w  w w .  ja  v  a 2  s.  com*/
 * @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);
    }
}