Example usage for javax.mail Message getContentType

List of usage examples for javax.mail Message getContentType

Introduction

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

Prototype

public String getContentType() throws MessagingException;

Source Link

Document

Returns the Content-Type of the content of this part.

Usage

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 av  a2s .  c om
      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:org.apache.hupa.server.utils.TestUtils.java

/**
 * Parses a mime message and returns an array of content-types.
 * Each line in the array represents a mime part and is indented
 * with spaces./* www.  j  a v  a 2s.c  om*/
 *
 * It's used in testing or debugging.
 *
 * @param msg
 * @return
 * @throws IOException
 * @throws MessagingException
 */
public static ArrayList<String> summaryzeContent(Message msg) throws IOException, MessagingException {
    return summaryzeContent(msg.getContent(), msg.getContentType(), 0);
}

From source file:org.jevis.emaildatasource.EMailManager.java

private static List<InputStream> getAnswerListFromAttach(List<Message> messages, String filename) {
    List<InputStream> input = new ArrayList<>();

    if (messages != null) {
        for (Message message : messages) {
            try {
                Logger.getLogger(EMailDataSource.class.getName()).log(Level.INFO,
                        "Content type: " + message.getContentType());

                if (message.isMimeType("multipart/*") && !message.isMimeType("multipart/encrypted")) {
                    Logger.getLogger(EMailDataSource.class.getName()).log(Level.INFO,
                            "Message content type" + message.getContentType());
                    //Message msg = (MimeMessage)message;
                    Object obj = message.getContent();
                    if (obj instanceof Multipart) {
                        input = prepareAnswer(message, filename);

                    } //instanceof

                } else {
                    Logger.getLogger(EMailDataSource.class.getName()).log(Level.INFO,
                            "Mimetype of message is not a multipart/*");

                }/*ww w.j  a  v  a  2s. c  o m*/
            } catch (MessagingException | IOException ex) {
                Logger.getLogger(EMailDataSource.class.getName()).log(Level.SEVERE,
                        "Could not process the attachment!", ex);
            }
        }
    }
    return input;
}

From source file:org.jevis.emaildatasource.EMailManager.java

private static List<InputStream> getAnswerListFromBody(List<Message> messages) {
    List<InputStream> input = new ArrayList<>();

    if (messages != null) {
        for (Message message : messages) {

            try {
                Logger.getLogger(EMailDataSource.class.getName()).log(Level.INFO,
                        "Content type: " + message.getContentType());

                if (message.isMimeType("text/plain")) {
                    Logger.getLogger(EMailDataSource.class.getName()).log(Level.INFO,
                            "Message content type: " + message.getContentType());
                    //Message msg = (MimeMessage)message;
                    String content = (String) message.getContent();

                    if (content.equals("") && content != null) {
                        //TODO;//input = prepareAnswer(message);
                    } //instanceof

                } else if (message.isMimeType("message/rfc822")) {
                    Logger.getLogger(EMailDataSource.class.getName()).log(Level.INFO,
                            "Message content type: " + message.getContentType());

                } else if (message.isMimeType("multipart/*")) {
                    Logger.getLogger(EMailDataSource.class.getName()).log(Level.INFO,
                            "Message content type" + message.getContentType());
                    //Message msg = (MimeMessage)message;
                    Object obj = message.getContent();

                    if (obj instanceof Multipart) {
                    }/*  w  w w  . j  a v a 2s.  c o  m*/
                } else {
                    Logger.getLogger(EMailDataSource.class.getName()).log(Level.INFO, "");

                }
            } //try
            catch (MessagingException | IOException ex) {
                Logger.getLogger(EMailDataSource.class.getName()).log(Level.SEVERE,
                        "Could not process the attachment!", ex);
            }
        }
    }
    return input;
}

From source file:org.apache.hupa.server.utils.MessageUtils.java

/**
 * Handle the parts of the given message. The method will call itself
 * recursively to handle all nested parts
 *
 * @param message the MimeMessage//from  w  ww . j  a  va 2 s.co  m
 * @param content the current processing Content
 * @param sbPlain the StringBuffer to fill with text
 * @param attachmentList ArrayList with attachments
 * @throws UnsupportedEncodingException
 * @throws MessagingException
 * @throws IOException
 */
public static boolean handleParts(Message message, Object content, StringBuffer sbPlain,
        ArrayList<MessageAttachment> attachmentList)
        throws UnsupportedEncodingException, MessagingException, IOException {
    boolean isHTML = false;
    if (content instanceof String) {
        if (message.getContentType().toLowerCase().startsWith("text/html")) {
            isHTML = true;
        } else {
            isHTML = false;
        }
        sbPlain.append((String) content);

    } else if (content instanceof Multipart) {

        Multipart mp = (Multipart) content;
        String multipartContentType = mp.getContentType().toLowerCase();

        String text = null;

        if (multipartContentType.startsWith("multipart/alternative")) {
            isHTML = handleMultiPartAlternative(mp, sbPlain);
        } else {
            for (int i = 0; i < mp.getCount(); i++) {
                Part part = mp.getBodyPart(i);

                String contentType = part.getContentType().toLowerCase();

                Boolean bodyRead = sbPlain.length() > 0;

                if (!bodyRead && contentType.startsWith("text/plain")) {
                    isHTML = false;
                    text = (String) part.getContent();
                } else if (!bodyRead && contentType.startsWith("text/html")) {
                    isHTML = true;
                    text = (String) part.getContent();
                } else if (!bodyRead && contentType.startsWith("message/rfc822")) {
                    // Extract the message and pass it
                    MimeMessage msg = (MimeMessage) part.getDataHandler().getContent();
                    isHTML = handleParts(msg, msg.getContent(), sbPlain, attachmentList);
                } else {
                    if (part.getFileName() != null) {
                        // Inline images are not added to the attachment
                        // list
                        // TODO: improve the in-line images detection
                        if (part.getHeader("Content-ID") == null) {
                            MessageAttachment attachment = new MessageAttachmentImpl();
                            attachment.setName(MimeUtility.decodeText(part.getFileName()));
                            attachment.setContentType(part.getContentType());
                            attachment.setSize(part.getSize());
                            attachmentList.add(attachment);
                        }
                    } else {
                        isHTML = handleParts(message, part.getContent(), sbPlain, attachmentList);
                    }
                }

            }
            if (text != null)
                sbPlain.append(text);
        }

    }
    return isHTML;
}

From source file:org.apache.hupa.server.handler.AbstractFetchMessagesHandler.java

private boolean hasAttachment(Message message) throws MessagingException {
    if (message.getContentType().startsWith("multipart/")) {
        try {//ww  w .  j av  a  2  s .c  om
            Object content;

            content = message.getContent();

            if (content instanceof Multipart) {
                Multipart mp = (Multipart) content;
                if (mp.getCount() > 1) {
                    for (int i = 0; i < mp.getCount(); i++) {
                        String disp = mp.getBodyPart(i).getDisposition();
                        if (disp != null && disp.equalsIgnoreCase(Part.ATTACHMENT)) {
                            return true;
                        }
                    }
                }

            }
        } catch (IOException e) {
            logger.error("Error while get content of message " + message.getMessageNumber());
        }

    }
    return false;
}

From source file:com.canoo.webtest.plugins.emailtest.EmailMessageStructureFilter.java

private void filterSimpleMessage(final String content, final Message message) throws MessagingException {
    final StringBuffer buf = new StringBuffer("<message type=\"Simple\" contentType=\"");
    buf.append(extractBaseContentType(message.getContentType())).append("\">").append(LS);
    processHeaders(buf, message);//  w  w w.  ja  va2 s.  c om
    appendUuencodedAttachments(buf, content);
    buf.append("</message>");
    defineAsCurrentResponse(buf.toString(), "text/xml");
}

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

/**
 * Import messages/* w  w w. j  a  v  a  2  s  . c om*/
 * http://www.jguru.com/faq/view.jsp?EID=26898
 * 
 * == Using Unique Identifier (UIDL) ==
 * Mail server assigns an unique identifier for every email in the same account. You can get as UIDL
 * for every email by MailInfo.UIDL property. To avoid receiving the same email twice, the best way is
 * storing the UIDL of email retrieved to a text file or database. Next time before you retrieve email,
 * compare your local uidl list with remote uidl. If this uidl exists in your local uidl list, don't
 * receive it; otherwise receive it.
 * 
 * == Different property of UIDL in POP3 and IMAP4 ==
 * UIDL is always unique in IMAP4 and it is always an incremental integer. UIDL in POP3 can be any valid
 * asc-ii characters, and an UIDL may be reused by POP3 server if email with this UIDL has been deleted
 * from the server. Hence you are advised to remove the uidl from your local uidl list if that uidl is
 * no longer exist on the POP3 server.
 * 
 * == Remarks ==
 * You should create different local uidl list for different email account, because the uidl is only
 * unique for the same account.
 */
public static String importMessages(String token, MailAccount ma) throws PathNotFoundException,
        ItemExistsException, VirusDetectedException, AccessDeniedException, RepositoryException,
        DatabaseException, UserQuotaExceededException, ExtensionException, AutomationException {
    log.debug("importMessages({}, {})", new Object[] { token, ma });
    Session session = Session.getDefaultInstance(getProperties());
    String exceptionMessage = null;

    try {
        // Open connection
        Store store = session.getStore(ma.getMailProtocol());
        store.connect(ma.getMailHost(), ma.getMailUser(), ma.getMailPassword());

        Folder folder = store.getFolder(ma.getMailFolder());
        folder.open(Folder.READ_WRITE);
        Message messages[] = null;

        if (folder instanceof IMAPFolder) {
            // IMAP folder UIDs begins at 1 and are supposed to be sequential.
            // Each folder has its own UIDs sequence, not is a global one.
            messages = ((IMAPFolder) folder).getMessagesByUID(ma.getMailLastUid() + 1, UIDFolder.LASTUID);
        } else {
            messages = folder.search(new FlagTerm(new Flags(Flags.Flag.SEEN), false));
        }

        for (int i = 0; i < messages.length; i++) {
            Message msg = messages[i];
            log.info(i + ": " + msg.getFrom()[0] + " " + msg.getSubject() + " " + msg.getContentType());
            log.info("Received: " + msg.getReceivedDate());
            log.info("Sent: " + msg.getSentDate());
            log.debug("{} -> {} - {}", new Object[] { i, msg.getSubject(), msg.getReceivedDate() });
            com.ikon.bean.Mail mail = messageToMail(msg);

            if (ma.getMailFilters().isEmpty()) {
                log.debug("Import in compatibility mode");
                String mailPath = getUserMailPath(ma.getUser());
                importMail(token, mailPath, true, folder, msg, ma, mail);
            } else {
                for (MailFilter mf : ma.getMailFilters()) {
                    log.debug("MailFilter: {}", mf);

                    if (checkRules(mail, mf.getFilterRules())) {
                        String mailPath = mf.getPath();
                        importMail(token, mailPath, mf.isGrouping(), folder, msg, ma, mail);
                    }
                }
            }

            // Set message as seen
            if (ma.isMailMarkSeen()) {
                msg.setFlag(Flags.Flag.SEEN, true);
            } else {
                msg.setFlag(Flags.Flag.SEEN, false);
            }

            // Delete read mail if requested
            if (ma.isMailMarkDeleted()) {
                msg.setFlag(Flags.Flag.DELETED, true);
            }

            // Set lastUid
            if (folder instanceof IMAPFolder) {
                long msgUid = ((IMAPFolder) folder).getUID(msg);
                log.info("Message UID: {}", msgUid);
                ma.setMailLastUid(msgUid);
                MailAccountDAO.update(ma);
            }
        }

        // Close connection
        log.debug("Expunge: {}", ma.isMailMarkDeleted());
        folder.close(ma.isMailMarkDeleted());
        store.close();
    } catch (NoSuchProviderException e) {
        log.error(e.getMessage(), e);
        exceptionMessage = e.getMessage();
    } catch (MessagingException e) {
        log.error(e.getMessage(), e);
        exceptionMessage = e.getMessage();
    } catch (IOException e) {
        log.error(e.getMessage(), e);
        exceptionMessage = e.getMessage();
    }

    log.debug("importMessages: {}", exceptionMessage);
    return exceptionMessage;
}

From source file:com.canoo.webtest.plugins.emailtest.EmailMessageContentFilter.java

protected void filterContent(final Message message) throws MessagingException {
    if (StringUtils.isEmpty(getPartIndex())) {
        try {/*from w ww  .  ja va 2  s . c om*/
            defineAsCurrentResponse(IOUtils.toString(message.getInputStream()), message.getContentType());
            return;
        } catch (IOException e) {
            throw new MessagingException("Error extracting message: " + e.getMessage());
        }
    }
    final int partIndex = ConversionUtil.convertToInt(getPartIndex(), 0);
    try {
        final Object content = message.getContent();
        if (content instanceof Multipart) {
            extractMultiPartMessage((Multipart) content, partIndex);
            return;
        }
        extractSimpleMessage((String) content, partIndex);
    } catch (IOException e) {
        LOG.error("Error processing email message: ", e);
        throw new MessagingException("Error processing email message: " + e.getMessage());
    }
}

From source file:com.canoo.webtest.plugins.emailtest.EmailMessageStructureFilter.java

private void filterMultiPartMessage(final Object content, final Message message) throws MessagingException {
    final Multipart parts = (Multipart) content;
    final StringBuffer buf = new StringBuffer();
    buf.append("<message type=\"MIME\" contentType=\"");
    buf.append(extractBaseContentType(message.getContentType())).append("\">").append(LS);
    processHeaders(buf, message);/*  ww  w  .ja  va2  s.co  m*/
    int count = parts.getCount();
    for (int i = 0; i < count; i++) {
        buf.append(processMessagePart(parts.getBodyPart(i)));
    }
    buf.append("</message>");
    defineAsCurrentResponse(buf.toString().getBytes(), "text/xml");
}