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:net.prhin.mailman.MailMan.java

public static void main(String[] args) {
    Properties props = new Properties();
    props.setProperty(resourceBundle.getString("mailman.mail.store"),
            resourceBundle.getString("mailman.protocol"));

    Session session = Session.getInstance(props);

    try {//from w ww .j  a va 2 s. c om

        Store store = session.getStore();
        store.connect(resourceBundle.getString("mailman.host"), resourceBundle.getString("mailman.user"),
                resourceBundle.getString("mailman.password"));
        Folder inbox = store.getFolder(resourceBundle.getString("mailman.folder"));
        inbox.open(Folder.READ_ONLY);
        inbox.getUnreadMessageCount();
        Message[] messages = inbox.getMessages();

        for (int i = 0; i <= messages.length / 2; i++) {
            Message tmpMessage = messages[i];

            Multipart multipart = (Multipart) tmpMessage.getContent();

            System.out.println("Multipart count: " + multipart.getCount());

            for (int j = 0; j < multipart.getCount(); j++) {
                BodyPart bodyPart = multipart.getBodyPart(j);

                if (!Part.ATTACHMENT.equalsIgnoreCase(bodyPart.getDisposition())) {
                    if (bodyPart.getContent().getClass().equals(MimeMultipart.class)) {
                        MimeMultipart mimeMultipart = (MimeMultipart) bodyPart.getContent();

                        for (int k = 0; k < mimeMultipart.getCount(); k++) {
                            if (mimeMultipart.getBodyPart(k).getFileName() != null) {
                                printFileContents(mimeMultipart.getBodyPart(k));
                            }
                        }
                    }
                } else {
                    printFileContents(bodyPart);
                }
            }
        }

        inbox.close(false);
        store.close();

    } catch (NoSuchProviderException e) {
        e.printStackTrace();
    } catch (MessagingException e) {
        e.printStackTrace();
    } catch (IOException e) {
        e.printStackTrace();
    }

}

From source file:net.fenyo.mail4hotspot.service.MailManager.java

public static void main(String[] args) throws NoSuchProviderException, MessagingException {
    System.out.println("Salut");

    //      trustSSL();

    /*       final Properties props = new Properties();
           props.put("mail.smtp.host", "my-mail-server");
           props.put("mail.from", "me@example.com");
           javax.mail.Session session = javax.mail.Session.getInstance(props, null);
           try {/*from w w  w.j a  v a 2 s .  c  o m*/
      MimeMessage msg = new MimeMessage(session);
      msg.setFrom();
      msg.setRecipients(Message.RecipientType.TO,
                        "you@example.com");
      msg.setSubject("JavaMail hello world example");
      msg.setSentDate(new Date());
      msg.setText("Hello, world!\n");
      Transport.send(msg);
              } catch (MessagingException mex) {
      System.out.println("send failed, exception: " + mex);
              }*/

    final Properties props = new Properties();

    //props.put("mail.host", "10.69.60.6");
    //props.put("mail.user", "fenyo");
    //props.put("mail.from", "fenyo@fenyo.net");
    //props.put("mail.transport.protocol", "smtps");

    //props.put("mail.store.protocol", "pop3s");

    // [javax.mail.Provider[STORE,imap,com.sun.mail.imap.IMAPStore,Sun Microsystems, Inc],
    // javax.mail.Provider[STORE,imaps,com.sun.mail.imap.IMAPSSLStore,Sun Microsystems, Inc],
    // javax.mail.Provider[TRANSPORT,smtp,com.sun.mail.smtp.SMTPTransport,Sun Microsystems, Inc],
    // javax.mail.Provider[TRANSPORT,smtps,com.sun.mail.smtp.SMTPSSLTransport,Sun Microsystems, Inc],
    // javax.mail.Provider[STORE,pop3,com.sun.mail.pop3.POP3Store,Sun Microsystems, Inc],
    // javax.mail.Provider[STORE,pop3s,com.sun.mail.pop3.POP3SSLStore,Sun Microsystems, Inc]]
    // final Provider[] providers = session.getProviders();

    javax.mail.Session session = javax.mail.Session.getInstance(props, null);

    session.setDebug(true);
    //session.setDebug(false);

    //       final Store store = session.getStore("pop3s");
    //       store.connect("10.69.60.6", 995, "fenyo", "PASSWORD");
    //       final Store store = session.getStore("imaps");
    //       store.connect("10.69.60.6", 993, "fenyo", "PASSWORD");
    //       System.out.println(store.getDefaultFolder().getMessageCount());

    //final Store store = session.getStore("pop3");
    final Store store = session.getStore("pop3s");
    //final Store store = session.getStore("imaps");

    //       store.addStoreListener(new StoreListener() {
    //          public void notification(StoreEvent e) {
    //          String s;
    //          if (e.getMessageType() == StoreEvent.ALERT)
    //          s = "ALERT: ";
    //          else
    //          s = "NOTICE: ";
    //          System.out.println("XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX: " + s + e.getMessage());
    //          }
    //       });

    //store.connect("10.69.60.6", 110, "fenyo", "PASSWORD");
    store.connect("pop.gmail.com", 995, "alexandre.fenyo@gmail.com", "PASSWORD");
    //store.connect("localhost", 110, "alexandre.fenyo@yahoo.com", "PASSWORD");
    //store.connect("localhost", 995, "fenyo@live.fr", "PASSWORD");
    //store.connect("localhost", 995, "thisisatestforalex@aol.fr", "PASSWORD");

    //       final Folder[] folders = store.getPersonalNamespaces();
    //       for (Folder f : folders) {
    //          System.out.println("Folder: " + f.getMessageCount());
    //          final Folder g = f.getFolder("INBOX");
    //          g.open(Folder.READ_ONLY);
    //          System.out.println("   g:" + g.getMessageCount());
    //       }

    final Folder inbox = store.getDefaultFolder().getFolder("INBOX");
    inbox.open(Folder.READ_ONLY);
    System.out.println("nmessages: " + inbox.getMessageCount());

    final Message[] messages = inbox.getMessages();

    for (Message message : messages) {
        System.out.println("message:");
        System.out.println("  size: " + message.getSize());
        try {
            if (message.getFrom() != null)
                System.out.println("  From: " + message.getFrom()[0]);
        } catch (final Exception ex) {
            System.out.println(ex.toString());
        }
        System.out.println("  content-type: " + message.getContentType());
        System.out.println("  disposition: " + message.getDisposition());
        System.out.println("  description: " + message.getDescription());
        System.out.println("  filename: " + message.getFileName());
        System.out.println("  line count: " + message.getLineCount());
        System.out.println("  message number: " + message.getMessageNumber());
        System.out.println("  subject: " + message.getSubject());
        try {
            if (message.getAllRecipients() != null)
                for (Address address : message.getAllRecipients())
                    System.out.println("  address: " + address);
        } catch (final Exception ex) {
            System.out.println(ex.toString());
        }
    }

    for (Message message : messages) {
        System.out.println("-----------------------------------------------------");
        Object content;
        try {
            content = message.getContent();
            if (javax.mail.Multipart.class.isInstance(content)) {
                System.out.println("CONTENT OBJECT CLASS: MULTIPART");
                final javax.mail.Multipart multipart = (javax.mail.Multipart) content;
                System.out.println("multipart content type: " + multipart.getContentType());
                System.out.println("multipart count: " + multipart.getCount());
                for (int i = 0; i < multipart.getCount(); i++) {
                    System.out.println("  multipart body[" + i + "]: " + multipart.getBodyPart(i));
                    BodyPart part = multipart.getBodyPart(i);
                    System.out.println("    content-type: " + part.getContentType());
                }

            } else if (String.class.isInstance(content)) {
                System.out.println("CONTENT IS A STRING: {" + content + "}");
            } else {
                System.out.println("CONTENT OBJECT CLASS: " + content.getClass().toString());
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    store.close();

}

From source file:com.mgmtp.jfunk.core.mail.MessageUtils.java

private static void parseMultipart(final StrBuilder sb, final Multipart multipart)
        throws MessagingException, IOException {
    for (int i = 0; i < multipart.getCount(); i++) {
        BodyPart bodyPart = multipart.getBodyPart(i);
        String disposition = bodyPart.getDisposition();

        if (disposition == null && bodyPart instanceof MimeBodyPart) { // not an attachment
            MimeBodyPart mimeBodyPart = (MimeBodyPart) bodyPart;

            if (mimeBodyPart.getContent() instanceof Multipart) {
                parseMultipart(sb, (Multipart) mimeBodyPart.getContent());
            } else {
                String body = (String) mimeBodyPart.getContent();
                sb.appendln(body);//from www.  j ava 2 s  .  c o  m
                sb.appendln("");
            }
        }
    }
}

From source file:org.nuxeo.ecm.core.convert.plugins.text.extractors.RFC822ToTextConverter.java

protected static List<Part> getAttachmentParts(Part p) throws Exception {
    List<Part> res = new ArrayList<Part>();
    if (p.isMimeType(MESSAGE_RFC822_MIMETYPE)) {
        res.addAll(getAttachmentParts((Part) p.getContent()));
    } else if (p.isMimeType("multipart/alternative")) {
        // only return one of the text alternatives
        Multipart mp = (Multipart) p.getContent();
        int count = mp.getCount();
        Part alternativePart = null;//from  ww w . j  a v a  2 s  . com
        for (int i = 0; i < count; i++) {
            Part subPart = mp.getBodyPart(i);
            if (subPart.isMimeType(TXT_MT)) {
                alternativePart = subPart;
                break;
            } else if (subPart.isMimeType("text/*")) {
                alternativePart = subPart;
            } else {
                res.addAll(getAttachmentParts(subPart));
            }
        }
        if (alternativePart != null) {
            res.add(alternativePart);
        }
    } else if (p.isMimeType("multipart/*")) {
        Multipart mp = (Multipart) p.getContent();
        int count = mp.getCount();
        for (int i = 0; i < count; i++) {
            res.addAll(getAttachmentParts(mp.getBodyPart(i)));
        }
    } else {
        res.add(p);
    }
    return res;
}

From source file:uidmsgshow.java

public static void dumpPart(Part p) throws Exception {
    if (p instanceof Message)
        dumpEnvelope((Message) p);//ww w  . j  av a  2 s  .co  m

    /* Dump input stream
    InputStream is = new BufferedInputStream(p.getInputStream());
    int c;
    while ((c = is.read()) != -1)
        System.out.write(c);
    */

    System.out.println("CONTENT-TYPE: " + p.getContentType());

    Object o = p.getContent();
    if (o instanceof String) {
        System.out.println("This is a String");
        System.out.println("---------------------------");
        System.out.println((String) o);
    } else if (o instanceof Multipart) {
        System.out.println("This is a Multipart");
        System.out.println("---------------------------");
        Multipart mp = (Multipart) o;
        int count = mp.getCount();
        for (int i = 0; i < count; i++)
            dumpPart(mp.getBodyPart(i));
    } else if (o instanceof Message) {
        System.out.println("This is a Nested Message");
        System.out.println("---------------------------");
        dumpPart((Part) o);
    } else if (o instanceof InputStream) {
        System.out.println("This is just an input stream");
        System.out.println("---------------------------");
        InputStream is = (InputStream) o;
        int c;
        while ((c = is.read()) != -1)
            System.out.write(c);
    }
}

From source file:uidmsgshow.java

public static void dumpPart(Part p) throws Exception {
    if (p instanceof Message)
        dumpEnvelope((Message) p);/*from   w ww.  j  av  a  2 s  . c  o  m*/

    /*
     * Dump input stream InputStream is = new
     * BufferedInputStream(p.getInputStream()); int c; while ((c = is.read()) !=
     * -1) System.out.write(c);
     */

    System.out.println("CONTENT-TYPE: " + p.getContentType());

    Object o = p.getContent();
    if (o instanceof String) {
        System.out.println("This is a String");
        System.out.println("---------------------------");
        System.out.println((String) o);
    } else if (o instanceof Multipart) {
        System.out.println("This is a Multipart");
        System.out.println("---------------------------");
        Multipart mp = (Multipart) o;
        int count = mp.getCount();
        for (int i = 0; i < count; i++)
            dumpPart(mp.getBodyPart(i));
    } else if (o instanceof Message) {
        System.out.println("This is a Nested Message");
        System.out.println("---------------------------");
        dumpPart((Part) o);
    } else if (o instanceof InputStream) {
        System.out.println("This is just an input stream");
        System.out.println("---------------------------");
        InputStream is = (InputStream) o;
        int c;
        while ((c = is.read()) != -1)
            System.out.write(c);
    }
}

From source file:org.nuxeo.cm.mail.actionpipe.ExtractMessageInformation.java

@SuppressWarnings("unchecked")
protected static void getAttachmentParts(Part p, String defaultFilename, MimetypeRegistry mimeService,
        ExecutionContext context) throws MessagingException, IOException {
    String filename = getFilename(p, defaultFilename);
    List<Blob> blobs = (List<Blob>) context.get(ATTACHMENTS_KEY);

    if (!p.isMimeType("multipart/*")) {
        String disp = p.getDisposition();
        // no disposition => consider it may be body
        if (disp == null && !context.containsKey(BODY_KEY)) {
            // this will need to be parsed
            context.put(BODY_KEY, p.getContent());
        } else if (disp != null
                && (disp.equalsIgnoreCase(Part.ATTACHMENT) || (disp.equalsIgnoreCase(Part.INLINE)
                        && !(p.isMimeType("text/*") || p.isMimeType("image/*"))))) {
            log.debug("Saving attachment to file " + filename);
            Blob blob = Blobs.createBlob(p.getInputStream());
            String mime = DEFAULT_BINARY_MIMETYPE;
            try {
                if (mimeService != null) {
                    ContentType contentType = new ContentType(p.getContentType());
                    mime = mimeService.getMimetypeFromFilenameAndBlobWithDefault(filename, blob,
                            contentType.getBaseType());
                }/*from w  w  w . j  a  v a2s .  c  om*/
            } catch (MimetypeDetectionException e) {
                log.error(e);
            }
            blob.setMimeType(mime);

            blob.setFilename(filename);

            blobs.add(blob);

            // for debug
            // File f = new File(filename);
            // ((MimeBodyPart) p).saveFile(f);

            log.debug("---------------------------");

        } else {
            log.debug(String.format("Ignoring part with type %s", p.getContentType()));
        }
    }

    if (p.isMimeType("multipart/*")) {
        log.debug("This is a Multipart");
        log.debug("---------------------------");
        Multipart mp = (Multipart) p.getContent();

        int count = mp.getCount();
        for (int i = 0; i < count; i++) {
            getAttachmentParts(mp.getBodyPart(i), defaultFilename, mimeService, context);
        }
    } else if (p.isMimeType(MESSAGE_RFC822_MIMETYPE)) {
        log.debug("This is a Nested Message");
        log.debug("---------------------------");
        getAttachmentParts((Part) p.getContent(), defaultFilename, mimeService, context);
    }

}

From source file:org.apache.hupa.server.preferences.InImapUserPreferencesStorage.java

/**
 * Opens the IMAP folder and read messages until it founds the magic subject,
 * then gets the attachment which contains the data and return the serialized object stored.
 *//*  w  w w. ja v  a  2 s  . c o m*/
protected static Object readUserPreferencesFromIMAP(Log logger, User user, IMAPStore iStore, String folderName,
        String magicType) throws MessagingException, IOException, ClassNotFoundException {
    Folder folder = iStore.getFolder(folderName);
    if (folder.exists()) {
        if (!folder.isOpen()) {
            folder.open(Folder.READ_WRITE);
        }
        Message message = null;
        Message[] msgs = folder.getMessages();
        for (Message msg : msgs) {
            if (magicType.equals(msg.getSubject())) {
                message = msg;
                break;
            }
        }
        if (message != null) {
            Object con = message.getContent();
            if (con instanceof Multipart) {
                Multipart mp = (Multipart) con;
                for (int i = 0; i < mp.getCount(); i++) {
                    BodyPart part = mp.getBodyPart(i);
                    if (part.getContentType().toLowerCase().startsWith(HUPA_DATA_MIME_TYPE)) {
                        ObjectInputStream ois = new ObjectInputStream(part.getInputStream());
                        Object o = ois.readObject();
                        ois.close();
                        logger.info("Returning user preferences of type " + magicType + " from imap folder + "
                                + folderName + " for user " + user);
                        return o;
                    }
                }
            }
        }
    }
    return null;
}

From source file:search.java

public static void dumpPart(Part p) throws Exception {
    if (p instanceof Message) {
        Message m = (Message) p;//  www  .j ava  2 s  . c om
        Address[] a;
        // FROM 
        if ((a = m.getFrom()) != null) {
            for (int j = 0; j < a.length; j++)
                System.out.println("FROM: " + a[j].toString());
        }

        // TO
        if ((a = m.getRecipients(Message.RecipientType.TO)) != null) {
            for (int j = 0; j < a.length; j++)
                System.out.println("TO: " + a[j].toString());
        }

        // SUBJECT
        System.out.println("SUBJECT: " + m.getSubject());

        // DATE
        Date d = m.getSentDate();
        System.out.println("SendDate: " + (d != null ? d.toLocaleString() : "UNKNOWN"));

        // FLAGS:
        Flags flags = m.getFlags();
        StringBuffer sb = new StringBuffer();
        Flags.Flag[] sf = flags.getSystemFlags(); // get the system flags

        boolean first = true;
        for (int i = 0; i < sf.length; i++) {
            String s;
            Flags.Flag f = sf[i];
            if (f == Flags.Flag.ANSWERED)
                s = "\\Answered";
            else if (f == Flags.Flag.DELETED)
                s = "\\Deleted";
            else if (f == Flags.Flag.DRAFT)
                s = "\\Draft";
            else if (f == Flags.Flag.FLAGGED)
                s = "\\Flagged";
            else if (f == Flags.Flag.RECENT)
                s = "\\Recent";
            else if (f == Flags.Flag.SEEN)
                s = "\\Seen";
            else
                continue; // skip it
            if (first)
                first = false;
            else
                sb.append(' ');
            sb.append(s);
        }

        String[] uf = flags.getUserFlags(); // get the user flag strings
        for (int i = 0; i < uf.length; i++) {
            if (first)
                first = false;
            else
                sb.append(' ');
            sb.append(uf[i]);
        }
        System.out.println("FLAGS = " + sb.toString());
    }

    System.out.println("CONTENT-TYPE: " + p.getContentType());

    /* Dump input stream
    InputStream is = ((MimeMessage)m).getInputStream();
    int c;
    while ((c = is.read()) != -1)
        System.out.write(c);
    */

    Object o = p.getContent();
    if (o instanceof String) {
        System.out.println("This is a String");
        System.out.println((String) o);
    } else if (o instanceof Multipart) {
        System.out.println("This is a Multipart");
        Multipart mp = (Multipart) o;
        int count = mp.getCount();
        for (int i = 0; i < count; i++)
            dumpPart(mp.getBodyPart(i));
    } else if (o instanceof InputStream) {
        System.out.println("This is just an input stream");
        InputStream is = (InputStream) o;
        int c;
        while ((c = is.read()) != -1)
            System.out.write(c);
    }
}

From source file:mitm.common.mail.MailUtils.java

/**
 * Converts any 8bit encoded parts to 7bit. Returns true if a part (or all parts) were converted from
 * 8bit to 7bit.//from   w  w  w  .j ava  2 s  . co  m
 * 
 * @param part
 * @throws MessagingException
 */
public static boolean convertTo7Bit(MimePart part) throws MessagingException, IOException {
    boolean converted = false;

    if (part.isMimeType("multipart/*")) {
        Multipart parts = (Multipart) part.getContent();

        int count = parts.getCount();

        for (int i = 0; i < count; i++) {
            boolean partConverted = convertTo7Bit((MimePart) parts.getBodyPart(i));

            if (partConverted) {
                converted = true;
            }
        }
    } else if ("8bit".equalsIgnoreCase(part.getEncoding())) {
        String encoding = part.isMimeType("text/*") ? "quoted-printable" : "base64";

        /*
         * We need to use a ByteArrayDataSource to make sure it will always be encoded
         */
        part.setDataHandler(
                new DataHandler(new ByteArrayDataSource(part.getInputStream(), part.getContentType())));

        part.setHeader("Content-Transfer-Encoding", encoding);
        part.addHeader("X-MIME-Autoconverted", "from 8bit to " + encoding + " by Djigzo");

        converted = true;
    }

    return converted;
}