Example usage for javax.mail Message getSize

List of usage examples for javax.mail Message getSize

Introduction

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

Prototype

public int getSize() throws MessagingException;

Source Link

Document

Return the size of the content of this part in bytes.

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 ww. ja v  a  2s  . com
      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.cubusmail.gwtui.server.services.ConvertUtil.java

/**
 * @param msg/*from w  w w  .j a  v a2  s .c  om*/
 * @return
 * @throws MessagingException
 */
public static GWTMessage convert(Message msg) throws MessagingException {

    GWTMessage result = new GWTMessage();
    result.setId(msg.getMessageNumber());
    result.setSubject(msg.getSubject());
    result.setFrom(MessageUtils.getMailAdressString(msg.getFrom(), AddressStringType.COMPLETE));
    result.setTo(MessageUtils.getMailAdressString(msg.getRecipients(Message.RecipientType.TO),
            AddressStringType.COMPLETE));
    result.setCc(MessageUtils.getMailAdressString(msg.getRecipients(Message.RecipientType.CC),
            AddressStringType.COMPLETE));
    result.setDate(msg.getSentDate());
    result.setSize(MessageUtils.calculateAttachmentSize(msg.getSize()));

    return result;
}

From source file:uidmsgshow.java

public static void dumpEnvelope(Message m) throws Exception {
    System.out.println("This is the message envelope");
    System.out.println("---------------------------");
    Address[] a;//from   w ww.j av  a  2  s. com
    // 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.toString() : "UNKNOWN"));

    // SIZE
    System.out.println("Size: " + m.getSize());

    // 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());

    // X-MAILER
    String[] hdrs = m.getHeader("X-Mailer");
    if (hdrs != null)
        System.out.println("X-Mailer: " + hdrs[0]);
    else
        System.out.println("X-Mailer NOT available");
}

From source file:uidmsgshow.java

public static void dumpEnvelope(Message m) throws Exception {
    System.out.println("This is the message envelope");
    System.out.println("---------------------------");
    Address[] a;/*w  ww.j a v a  2s .c o m*/
    // 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.toString() : "UNKNOWN"));

    // SIZE
    System.out.println("Size: " + m.getSize());

    // 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());

    // X-MAILER
    String[] hdrs = m.getHeader("X-Mailer");
    if (hdrs != null)
        System.out.println("X-Mailer: " + hdrs[0]);
    else
        System.out.println("X-Mailer NOT available");
}

From source file:de.mmichaelis.maven.mojo.MailDevelopersMojoTest.java

private void doTestMailToDevelopers(final int numDevelopers) throws Exception {
    final MavenProject project = mock(MavenProject.class);
    when(project.getDevelopers()).thenReturn(Arrays.asList(Arrays.copyOf(developers, numDevelopers)));
    mojoWrapper.setProject(project);//from   ww  w .  j  a  v  a2s . c o m
    mojoWrapper.execute();
    for (int i = 0; i < numDevelopers; i++) {
        final Developer developer = developers[i];
        final Mailbox inbox = Mailbox.get(developer.getEmail());
        assertEquals("Should have received one email.", 1, inbox.size());
        final Message message = inbox.get(0);
        final InputStream stream = message.getInputStream();
        final int messageSize = message.getSize();
        final StringWriter writer;
        try {
            writer = new StringWriter(messageSize < 0 ? 512 : messageSize);
            IOUtils.copy(stream, writer);
        } finally {
            stream.close();
        }
        LOG.debug("Mail for one developer:\n" + writer.toString());
    }
}

From source file:com.cubusmail.server.services.ConvertUtil.java

/**
 * @param folder/*from w  w w  . java 2 s . c  o  m*/
 * @param msg
 * @param result
 * @throws MessagingException
 */
private static void convertToStringArray(IMAPFolder folder, Message msg, GWTMessageRecord result,
        DateFormat dateFormat, NumberFormat decimalFormat) throws MessagingException {

    result.setId(Long.toString(folder.getUID(msg)));
    try {
        result.setAttachmentImage(MessageUtils.hasAttachments(msg) ? ImageProvider.MSG_ATTACHMENT : null);
    } catch (IOException e) {
        // do nothing
    }
    GWTMessageFlags flags = new GWTMessageFlags();
    flags.setDeleted(msg.isSet(Flags.Flag.DELETED));
    flags.setUnread(!msg.isSet(Flags.Flag.SEEN));
    flags.setAnswered(msg.isSet(Flags.Flag.ANSWERED));
    flags.setDraft(msg.isSet(Flags.Flag.DRAFT));
    result.setFlags(flags);

    result.setProrityImage(getPriorityImage(msg));
    result.setSubject(HtmlUtils.htmlEscape(msg.getSubject()));

    result.setFrom(
            HtmlUtils.htmlEscape(MessageUtils.getMailAdressString(msg.getFrom(), AddressStringType.PERSONAL)));
    result.setTo(HtmlUtils.htmlEscape(
            MessageUtils.getMailAdressString(msg.getRecipients(RecipientType.TO), AddressStringType.PERSONAL)));
    if (msg.getSentDate() != null) {
        result.setSendDateString(HtmlUtils.htmlEscape(dateFormat.format(msg.getSentDate())));
        result.setSendDate(msg.getSentDate());
    }

    int msgSize = MessageUtils.calculateAttachmentSize(msg.getSize());
    result.setSizeString(HtmlUtils.htmlEscape(MessageUtils.formatPartSize(msgSize, decimalFormat)));
    result.setSize(msgSize);
}

From source file:com.cubusmail.gwtui.server.services.ConvertUtil.java

/**
 * @param folder//from  ww w .  j  a v a  2 s.c  om
 * @param msg
 * @param result
 * @throws MessagingException
 */
public static void convertToStringArray(IMailFolder folder, Message msg, String[] result, DateFormat dateFormat,
        NumberFormat decimalFormat) throws MessagingException {

    result[MessageListFields.ID.ordinal()] = Long.toString(folder.getUID(msg));
    try {
        result[MessageListFields.ATTACHMENT_FLAG.ordinal()] = Boolean
                .toString(MessageUtils.hasAttachments(msg));
    } catch (IOException e) {
        // do nothing
    }
    result[MessageListFields.READ_FLAG.ordinal()] = Boolean.toString(msg.isSet(Flags.Flag.SEEN));
    result[MessageListFields.DELETED_FLAG.ordinal()] = Boolean.toString(msg.isSet(Flags.Flag.DELETED));
    result[MessageListFields.ANSWERED_FLAG.ordinal()] = Boolean.toString(msg.isSet(Flags.Flag.ANSWERED));
    result[MessageListFields.DRAFT_FLAG.ordinal()] = Boolean.toString(msg.isSet(Flags.Flag.DRAFT));
    result[MessageListFields.PRIORITY.ordinal()] = Integer.toString(MessageUtils.getMessagePriority(msg));
    if (!StringUtils.isEmpty(msg.getSubject())) {
        result[MessageListFields.SUBJECT.ordinal()] = msg.getSubject();
    }
    result[MessageListFields.FROM.ordinal()] = MessageUtils.getMailAdressString(msg.getFrom(),
            AddressStringType.PERSONAL);
    result[MessageListFields.TO.ordinal()] = MessageUtils
            .getMailAdressString(msg.getRecipients(RecipientType.TO), AddressStringType.PERSONAL);
    if (msg.getSentDate() != null) {
        result[MessageListFields.DATE.ordinal()] = dateFormat.format(msg.getSentDate());
    }
    result[MessageListFields.SIZE.ordinal()] = MessageUtils
            .formatPartSize(MessageUtils.calculateAttachmentSize(msg.getSize()), decimalFormat);
}

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

/**
 * Convert Mime Message to Mail/*from  www.  j ava 2s .  c om*/
 */
public static Mail messageToMail(Message msg) throws MessagingException, IOException {
    com.openkm.bean.Mail mail = new com.openkm.bean.Mail();
    Calendar receivedDate = Calendar.getInstance();
    Calendar sentDate = Calendar.getInstance();

    // Can be void
    if (msg.getReceivedDate() != null) {
        receivedDate.setTime(msg.getReceivedDate());
    }

    // Can be void
    if (msg.getSentDate() != null) {
        sentDate.setTime(msg.getSentDate());
    }

    String body = getText(msg);

    // log.info("getText: "+body);
    if (body.charAt(0) == 'H') {
        mail.setMimeType(MimeTypeConfig.MIME_HTML);
    } else if (body.charAt(0) == 'T') {
        mail.setMimeType(MimeTypeConfig.MIME_TEXT);
    } else {
        mail.setMimeType(MimeTypeConfig.MIME_UNDEFINED);
    }

    if (msg.getFrom() != null && msg.getFrom().length > 0) {
        mail.setFrom(addressToString(msg.getFrom()[0]));
    }

    mail.setSize(msg.getSize());
    mail.setContent(body.substring(1));
    mail.setSubject((msg.getSubject() == null || msg.getSubject().isEmpty()) ? NO_SUBJECT : msg.getSubject());
    mail.setTo(addressToString(msg.getRecipients(Message.RecipientType.TO)));
    mail.setCc(addressToString(msg.getRecipients(Message.RecipientType.CC)));
    mail.setBcc(addressToString(msg.getRecipients(Message.RecipientType.BCC)));
    mail.setReceivedDate(receivedDate);
    mail.setSentDate(sentDate);

    return mail;
}

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

public static IndexableMailMessage fromJavaMailMessage(final Message jmm, final boolean withTextContent,
        final boolean withAttachments, final boolean stripTags, List<String> headersToFields)
        throws MessagingException, IOException {
    final IndexableMailMessage im = new IndexableMailMessage();

    @SuppressWarnings("unchecked")
    final Enumeration<Header> allHeaders = jmm.getAllHeaders();

    final Set<IndexableHeader> headerList = new HashSet<IndexableHeader>();
    while (allHeaders.hasMoreElements()) {
        final Header h = allHeaders.nextElement();
        headerList.add(new IndexableHeader(h.getName(), h.getValue()));
    }//  www . ja  v  a 2  s . c o m

    im.setHeaders(headerList.toArray(new IndexableHeader[headerList.size()]));

    im.setSelectedHeaders(extractHeaders(im.getHeaders(), headersToFields));

    if (jmm.getFolder() instanceof POP3Folder) {
        im.setPopId(((POP3Folder) jmm.getFolder()).getUID(jmm));
        im.setMailboxType("POP");

    } else {
        im.setMailboxType("IMAP");
    }

    if (jmm.getFolder() instanceof UIDFolder) {
        im.setUid(((UIDFolder) jmm.getFolder()).getUID(jmm));
    }

    im.setFolderFullName(jmm.getFolder().getFullName());

    im.setFolderUri(jmm.getFolder().getURLName().toString());

    im.setContentType(jmm.getContentType());
    im.setSubject(jmm.getSubject());
    im.setSize(jmm.getSize());
    im.setSentDate(jmm.getSentDate());

    if (jmm.getReceivedDate() != null) {
        im.setReceivedDate(jmm.getReceivedDate());
    }

    if (jmm.getFrom() != null && jmm.getFrom().length > 0) {
        im.setFrom(Address.fromJavaMailAddress(jmm.getFrom()[0]));
    }

    if (jmm.getRecipients(RecipientType.TO) != null) {
        im.setTo(Address.fromJavaMailAddress(jmm.getRecipients(RecipientType.TO)));
    }

    if (jmm.getRecipients(RecipientType.CC) != null) {
        im.setCc(Address.fromJavaMailAddress(jmm.getRecipients(RecipientType.CC)));
    }

    if (jmm.getRecipients(RecipientType.BCC) != null) {
        im.setBcc(Address.fromJavaMailAddress(jmm.getRecipients(RecipientType.BCC)));
    }

    if (withTextContent) {

        // try {

        String textContent = getText(jmm, 0);

        if (stripTags) {
            textContent = stripTags(textContent);
        }

        im.setTextContent(textContent);
        // } catch (final Exception e) {
        // logger.error("Unable to retrieve text content for message {} due to {}",
        // e, ((MimeMessage) jmm).getMessageID(), e);
        // }
    }

    if (withAttachments) {

        try {
            final Object content = jmm.getContent();

            // look for attachments
            if (jmm.isMimeType("multipart/*") && content instanceof Multipart) {
                List<ESAttachment> attachments = new ArrayList<ESAttachment>();

                final Multipart multipart = (Multipart) content;

                for (int i = 0; i < multipart.getCount(); i++) {
                    final BodyPart bodyPart = multipart.getBodyPart(i);
                    if (!Part.ATTACHMENT.equalsIgnoreCase(bodyPart.getDisposition())
                            && !StringUtils.isNotBlank(bodyPart.getFileName())) {
                        continue; // dealing with attachments only
                    }
                    final InputStream is = bodyPart.getInputStream();
                    final byte[] bytes = IOUtils.toByteArray(is);
                    IOUtils.closeQuietly(is);
                    attachments.add(new ESAttachment(bodyPart.getContentType(), bytes, bodyPart.getFileName()));
                }

                if (!attachments.isEmpty()) {
                    im.setAttachments(attachments.toArray(new ESAttachment[attachments.size()]));
                    im.setAttachmentCount(im.getAttachments().length);
                    attachments.clear();
                    attachments = null;
                }

            }
        } catch (final Exception e) {
            logger.error(
                    "Error indexing attachments (message will be indexed but without attachments) due to {}", e,
                    e.toString());
        }

    }

    im.setFlags(IMAPUtils.toStringArray(jmm.getFlags()));
    im.setFlaghashcode(jmm.getFlags().hashCode());

    return im;
}

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

public static IndexableMailMessage fromJavaMailMessage(final Message jmm, final boolean withTextContent,
        final boolean withHtmlContent, final boolean preferHtmlContent, final boolean withAttachments,
        final boolean stripTags, List<String> headersToFields) throws MessagingException, IOException {
    final IndexableMailMessage im = new IndexableMailMessage();

    @SuppressWarnings("unchecked")
    final Enumeration<Header> allHeaders = jmm.getAllHeaders();

    final Set<IndexableHeader> headerList = new HashSet<IndexableHeader>();
    while (allHeaders.hasMoreElements()) {
        final Header h = allHeaders.nextElement();
        headerList.add(new IndexableHeader(h.getName(), h.getValue()));
    }/*w w w  . ja  v  a 2  s .  c om*/

    im.setHeaders(headerList.toArray(new IndexableHeader[headerList.size()]));

    im.setSelectedHeaders(extractHeaders(im.getHeaders(), headersToFields));

    if (jmm.getFolder() instanceof POP3Folder) {
        im.setPopId(((POP3Folder) jmm.getFolder()).getUID(jmm));
        im.setMailboxType("POP");

    } else {
        im.setMailboxType("IMAP");
    }

    if (jmm.getFolder() instanceof UIDFolder) {
        im.setUid(((UIDFolder) jmm.getFolder()).getUID(jmm));
    }

    im.setFolderFullName(jmm.getFolder().getFullName());

    im.setFolderUri(jmm.getFolder().getURLName().toString());

    im.setContentType(jmm.getContentType());
    im.setSubject(jmm.getSubject());
    im.setSize(jmm.getSize());
    im.setSentDate(jmm.getSentDate());

    if (jmm.getReceivedDate() != null) {
        im.setReceivedDate(jmm.getReceivedDate());
    }

    if (jmm.getFrom() != null && jmm.getFrom().length > 0) {
        im.setFrom(Address.fromJavaMailAddress(jmm.getFrom()[0]));
    }

    if (jmm.getRecipients(RecipientType.TO) != null) {
        im.setTo(Address.fromJavaMailAddress(jmm.getRecipients(RecipientType.TO)));
    }

    if (jmm.getRecipients(RecipientType.CC) != null) {
        im.setCc(Address.fromJavaMailAddress(jmm.getRecipients(RecipientType.CC)));
    }

    if (jmm.getRecipients(RecipientType.BCC) != null) {
        im.setBcc(Address.fromJavaMailAddress(jmm.getRecipients(RecipientType.BCC)));
    }

    if (withTextContent) {

        // try {

        String textContent = getText(jmm, 0, preferHtmlContent);

        if (stripTags) {
            textContent = stripTags(textContent);
        }

        im.setTextContent(textContent);
        // } catch (final Exception e) {
        // logger.error("Unable to retrieve text content for message {} due to {}",
        // e, ((MimeMessage) jmm).getMessageID(), e);
        // }
    }

    if (withHtmlContent) {

        // try {

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

        im.setHtmlContent(htmlContent);
        // } catch (final Exception e) {
        // logger.error("Unable to retrieve text content for message {} due to {}",
        // e, ((MimeMessage) jmm).getMessageID(), e);
        // }
    }

    if (withAttachments) {

        try {
            final Object content = jmm.getContent();

            // look for attachments
            if (jmm.isMimeType("multipart/*") && content instanceof Multipart) {
                List<ESAttachment> attachments = new ArrayList<ESAttachment>();

                final Multipart multipart = (Multipart) content;

                for (int i = 0; i < multipart.getCount(); i++) {
                    final BodyPart bodyPart = multipart.getBodyPart(i);
                    if (!Part.ATTACHMENT.equalsIgnoreCase(bodyPart.getDisposition())
                            && !StringUtils.isNotBlank(bodyPart.getFileName())) {
                        continue; // dealing with attachments only
                    }
                    final InputStream is = bodyPart.getInputStream();
                    final byte[] bytes = IOUtils.toByteArray(is);
                    IOUtils.closeQuietly(is);
                    attachments.add(new ESAttachment(bodyPart.getContentType(), bytes, bodyPart.getFileName()));
                }

                if (!attachments.isEmpty()) {
                    im.setAttachments(attachments.toArray(new ESAttachment[attachments.size()]));
                    im.setAttachmentCount(im.getAttachments().length);
                    attachments.clear();
                    attachments = null;
                }

            }
        } catch (final Exception e) {
            logger.error(
                    "Error indexing attachments (message will be indexed but without attachments) due to {}", e,
                    e.toString());
        }

    }

    im.setFlags(IMAPUtils.toStringArray(jmm.getFlags()));
    im.setFlaghashcode(jmm.getFlags().hashCode());

    return im;
}