Example usage for javax.mail Multipart getCount

List of usage examples for javax.mail Multipart getCount

Introduction

In this page you can find the example usage for javax.mail Multipart getCount.

Prototype

public synchronized int getCount() throws MessagingException 

Source Link

Document

Return the number of enclosed BodyPart objects.

Usage

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 ww w. j  a v  a  2 s  .  co  m
 * @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:com.glaf.mail.business.MailBean.java

/**
 * ??//from  w  w  w . j a  v a 2  s.  c o  m
 * 
 * @param part
 * @return
 * @throws MessagingException
 * @throws IOException
 */
public boolean isContainAttch(Part part) throws MessagingException, IOException {
    boolean flag = false;
    if (part.isMimeType("multipart/*")) {
        Multipart multipart = (Multipart) part.getContent();
        int count = multipart.getCount();
        for (int i = 0; i < count; i++) {
            BodyPart bodypart = multipart.getBodyPart(i);
            String dispostion = bodypart.getDisposition();
            if ((dispostion != null)
                    && (dispostion.equals(Part.ATTACHMENT) || dispostion.equals(Part.INLINE))) {
                flag = true;
            } else if (bodypart.isMimeType("multipart/*")) {
                flag = isContainAttch(bodypart);
            } else {
                String contentType = bodypart.getContentType();
                if (contentType.toLowerCase().indexOf("appliaction") != -1) {
                    flag = true;
                }
                if (contentType.toLowerCase().indexOf("name") != -1) {
                    flag = true;
                }
            }
        }
    } else if (part.isMimeType("message/rfc822")) {
        flag = isContainAttch((Part) part.getContent());
    }

    return flag;
}

From source file:com.consol.citrus.mail.message.MailMessageConverter.java

/**
 * Construct multipart body with first part being the body content and further parts being the attachments.
 * @param body//from w  w  w . j  a  v a  2  s. co m
 * @return
 * @throws IOException
 */
private BodyPart handleMultiPart(Multipart body) throws IOException, MessagingException {
    BodyPart bodyPart = null;
    for (int i = 0; i < body.getCount(); i++) {
        MimePart entity = (MimePart) body.getBodyPart(i);

        if (bodyPart == null) {
            bodyPart = handlePart(entity);
        } else {
            BodyPart attachment = handlePart(entity);
            bodyPart.addPart(new AttachmentPart(attachment.getContent(),
                    parseContentType(attachment.getContentType()), entity.getFileName()));
        }
    }

    return bodyPart;
}

From source file:org.apache.oozie.action.email.TestEmailActionExecutor.java

private void assertAttachment(String attachtag, int attachCount, String content1, String content2)
        throws Exception {
    sendAndReceiveEmail(attachtag);/*from  ww  w  .j a  v  a 2s  . co m*/
    MimeMessage retMeg = server.getReceivedMessages()[0];
    Multipart retParts = (Multipart) (retMeg.getContent());
    int numAttach = 0;
    for (int i = 0; i < retParts.getCount(); i++) {
        BodyPart bp = retParts.getBodyPart(i);
        String disp = bp.getDisposition();
        String retValue = IOUtils.toString(bp.getInputStream());
        if (disp != null && (disp.equals(BodyPart.ATTACHMENT))) {
            assertTrue(retValue.equals(content1) || retValue.equals(content2));
            numAttach++;
        } else {
            assertEquals("This is a test mail", retValue);
        }
    }
    assertEquals(attachCount, numAttach);
}

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  2s  .c om*/
 * 
 * @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:com.glaf.mail.business.MailBean.java

/**
 * ?//from   www  .j av  a2 s.c  o m
 * 
 * @param part
 * @throws MessagingException
 * @throws IOException
 */
public void parseAttachment(Part part) throws MessagingException, IOException {
    String filename = "";
    if (part.isMimeType("multipart/*")) {
        Multipart mp = (Multipart) part.getContent();
        for (int i = 0; i < mp.getCount(); i++) {
            BodyPart mpart = mp.getBodyPart(i);
            String dispostion = mpart.getDisposition();
            if ((dispostion != null)
                    && (dispostion.equals(Part.ATTACHMENT) || dispostion.equals(Part.INLINE))) {
                filename = mpart.getFileName();
                if (filename != null) {
                    logger.debug("orig filename=" + filename);
                    if (filename.indexOf("?") != -1) {
                        filename = new String(filename.getBytes("GBK"), "UTF-8");
                    }
                    if (filename.toLowerCase().indexOf("gb2312") != -1) {
                        filename = MimeUtility.decodeText(filename);
                    }
                    filename = MailUtils.convertString(filename);
                    logger.debug("filename=" + filename);
                    parseFileContent(filename, mpart.getInputStream());
                }
            } else if (mpart.isMimeType("multipart/*")) {
                parseAttachment(mpart);
            } else {
                filename = mpart.getFileName();
                if (filename != null) {
                    logger.debug("orig filename=" + filename);
                    if (filename.indexOf("?") != -1) {
                        filename = new String(filename.getBytes("GBK"), "UTF-8");
                    }
                    if (filename.toLowerCase().indexOf("gb2312") != -1) {
                        filename = MimeUtility.decodeText(filename);
                    }
                    filename = MailUtils.convertString(filename);
                    parseFileContent(filename, mpart.getInputStream());
                    logger.debug("filename=" + filename);
                }
            }
        }

    } else if (part.isMimeType("message/rfc822")) {
        parseAttachment((Part) part.getContent());
    }
}

From source file:org.alfresco.email.server.impl.subetha.SubethaEmailMessage.java

private void parseMessagePart(Part messagePart) {
    try {/*w  w  w .java2s. c  om*/
        if (messagePart.isMimeType(MIME_PLAIN_TEXT) || messagePart.isMimeType(MIME_HTML_TEXT)) {
            if (log.isDebugEnabled()) {
                log.debug("Text or HTML part was found. ContentType: " + messagePart.getContentType());
            }
            addBody(messagePart);
        } else if (messagePart.isMimeType(MIME_XML_TEXT)) {
            if (log.isDebugEnabled()) {
                log.debug("XML part was found.");
            }
            addAttachment(messagePart);
        } else if (messagePart.isMimeType(MIME_APPLICATION)) {
            if (log.isDebugEnabled()) {
                log.debug("Application part was found.");
            }
            addAttachment(messagePart);
        } else if (messagePart.isMimeType(MIME_IMAGE)) {
            if (log.isDebugEnabled()) {
                log.debug("Image part was found.");
            }
            addAttachment(messagePart);
        } else if (messagePart.isMimeType(MIME_MULTIPART)) {
            // if multipart, this method will be called recursively
            // for each of its parts
            Multipart mp = (Multipart) messagePart.getContent();
            int count = mp.getCount();

            if (log.isDebugEnabled()) {
                log.debug("MULTIPART with " + count + " part(s) found. Processin each part...");
            }
            for (int i = 0; i < count; i++) {
                BodyPart bp = mp.getBodyPart(i);
                if (bp.getContent() instanceof MimeMultipart) {
                    // It's multipart.  Recurse.
                    parseMessagePart(bp);
                } else {
                    // It's the body
                    addBody(bp);
                }
            }

            if (log.isDebugEnabled()) {
                log.debug("MULTIPART processed.");
            }

        } else if (messagePart.isMimeType(MIME_RFC822)) {
            // if rfc822, call this method with its content as the part
            if (log.isDebugEnabled()) {
                log.debug("MIME_RFC822 part found. Processing inside part...");
            }

            parseMessagePart((Part) messagePart.getContent());

            if (log.isDebugEnabled()) {
                log.debug("MIME_RFC822 processed.");
            }

        } else {
            // if all else fails, put this in the attachments map.
            // Actually we don't know what it is.
            if (log.isDebugEnabled()) {
                log.debug("Unrecognized part was found. Put it into attachments.");
            }
            addAttachment(messagePart);
        }
    } catch (IOException e) {
        throw new EmailMessageException(ERR_PARSE_MESSAGE, e.getMessage());
    } catch (MessagingException e) {
        throw new EmailMessageException(ERR_PARSE_MESSAGE, e.getMessage());
    }
}

From source file:com.riq.MailHandlerServlet.java

private String getText(Part p) throws MessagingException, IOException {
    //    log.info("Message S Zero");
    //    log.info("Inside MailServlet getText");

    if (p.isMimeType("text/*")) {
        String s = (String) p.getContent();
        log.info("Message S1: " + s);
        boolean textIsHtml = p.isMimeType("text/html");
        return s;
    }/*  w  w w.ja va2 s  .  c om*/

    if (p.isMimeType("multipart/alternative")) {
        Multipart mp = (Multipart) p.getContent();
        String text = null;
        for (int i = 0; i < mp.getCount(); i++) {
            Part bp = mp.getBodyPart(i);
            if (bp.isMimeType("text/plain")) {
                if (text == null)
                    text = getText(bp);
                log.info("Message S2: " + text);
                continue;
            } else if (bp.isMimeType("text/html")) {
                String s = getText(bp);
                if (s != null)
                    log.info("Message S3: " + s);
                return s;
            } else if (bp.isMimeType("message/rfc822")) {
                Object nestedObject = "";
                nestedObject = bp.getContent();
                Multipart nestedPart = (Multipart) nestedObject;
                BodyPart nestedBodyPart = nestedPart.getBodyPart(0);
                String s = getText(nestedBodyPart);
                if (s != null)
                    log.info("Message Nested: " + s);
                return s;
            } else {
                log.info("Message nada");
                return getText(bp);
            }
        }
        return text;

    } else if (p.isMimeType("multipart/*")) {
        Multipart mp = (Multipart) p.getContent();
        for (int i = 0; i < mp.getCount(); i++) {
            String s = getText(mp.getBodyPart(i));
            if (s != null) {
                log.info("Message S4: " + s);
                return s;
            }
        }
    }
    return null;
}

From source file:com.googlecode.gmail4j.javamail.JavaMailGmailMessage.java

/**
 * Gets plain text version of the content. Has some limitations - won't 
 * handle nested attachments well./*  w  w w .ja v a2 s  .  co m*/
 * 
 * @return String representation of the message
 */
@Override
public String getContentText() {
    try {
        Object content = source.getContent();
        StringBuilder result = new StringBuilder();
        if (content instanceof String) {
            result.append(content);
        } else if (content instanceof Multipart) {
            Multipart parts = (Multipart) content;
            for (int i = 0; i < parts.getCount(); i++) {
                BodyPart part = parts.getBodyPart(i);
                if (part.getContent() instanceof String) {
                    result.append(part.getContent());
                }
            }
        }
        return result.toString();
    } catch (Exception e) {
        throw new GmailException(
                "Failed getting text content from " + "JavaMailGmailMessage. You could try handling "
                        + "((JavaMailGmailMessage).getMessage()) manually",
                e);
    }
}

From source file:com.googlecode.gmail4j.javamail.JavaMailGmailMessage.java

@Override
public List<GmailAttachment> getAttachements() {
    List<GmailAttachment> result = new ArrayList<GmailAttachment>();

    try {/*from   w w  w .j  av a 2 s .  c o m*/
        Object content = this.source.getContent();
        if (content instanceof Multipart) {
            Multipart multipart = (Multipart) content;
            for (int i = 0; i < multipart.getCount(); i++) {
                Part bodyPart = multipart.getBodyPart(i);
                if (bodyPart.getDisposition() != null) {
                    if (bodyPart.getDisposition().equalsIgnoreCase(Part.ATTACHMENT)) {
                        result.add(new GmailAttachment(i, bodyPart.getFileName(), bodyPart.getContentType(),
                                bodyPart.getInputStream()));
                    }
                }
            }
        }
    } catch (Exception e) {
        throw new GmailException("Failed to get attachements", e);
    }

    return result;
}