Example usage for javax.mail Message isMimeType

List of usage examples for javax.mail Message isMimeType

Introduction

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

Prototype

public boolean isMimeType(String mimeType) throws MessagingException;

Source Link

Document

Is this Part of the specified MIME type?

Usage

From source file:com.cubusmail.mail.util.MessageUtils.java

/**
 * @param msg/*  w ww. ja v  a  2  s .  c om*/
 * @return
 * @throws MessagingException
 */
public static boolean isHtmlMessage(Message msg) throws MessagingException {

    return msg.isMimeType("text/html");
}

From source file:io.lavagna.service.MailTicketService.java

private String getTextFromMessage(Message message) throws MessagingException, IOException {
    String result = "";
    if (message.isMimeType("text/plain")) {
        result = message.getContent().toString();
    } else if (message.isMimeType("multipart/*")) {
        MimeMultipart mimeMultipart = (MimeMultipart) message.getContent();
        result = getTextFromMimeMultipart(mimeMultipart);
    }//  w w  w .  j a  v a  2 s  .  c  o m
    return result;
}

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

public String getMessageContentString(final Message message) throws IOException, MessagingException {
    final Object content = message.getContent();
    if (String.class.isInstance(content))
        // content-type: text/{plain, html, etc.}
        // prfrer isMimeType(...)  getContentType().equals(...) car getContentType() peut contenir aussi le charset et renvoyer une string comme suit : << text/html; charset="us-ascii" >>
        if (message.isMimeType("text/html"))
            return GenericTools.html2Text((String) content);
        else if (message.isMimeType("text/plain"))
            return (String) content;
        else {//from  ww w  .j a v a 2  s.c  om
            log.warn("message content-type not handled: " + message.getContentType()
                    + " -> downgrading to String");
            return (String) content;
        }
    else if (MimeMultipart.class.isInstance(content)) {
        boolean mixed = false;
        if (message.isMimeType("multipart/mixed"))
            mixed = true;
        else if (message.isMimeType("multipart/alternative"))
            mixed = false;
        else {
            log.warn("multipart content-type not handled: " + message.getContentType()
                    + " -> downgrading to multipart/mixed");
            mixed = true;
        }
        return getMultipartContentString((MimeMultipart) content, mixed);
    } else {
        log.warn("invalid message content type and class: " + content.getClass().toString() + " - "
                + message.getContentType());
        return "";
    }
}

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()));
    }/*from w ww.j  a  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);

        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()));
    }/*from w  w  w .  j  a  va  2s  .  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, 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;
}

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

private void doReceiveMessages() throws Exception {

    log.debug("Checking mail ");

    String host = Turbine.getConfiguration().getString("mail.pop3.host");
    String username = Turbine.getConfiguration().getString("mail.pop3.user");
    String password = Turbine.getConfiguration().getString("mail.pop3.password");

    // Create empty properties
    Properties props = new Properties();

    // Get session
    Session session = Session.getDefaultInstance(props, null);

    // Get the store
    Store store = session.getStore("pop3");

    // Connect to store
    store.connect(host, username, password);

    // Get folder
    Folder folder = store.getFolder("INBOX");

    // Open read-only
    folder.open(Folder.READ_WRITE);//from  www .  ja  va2  s. com

    // Get attributes & flags for all messages
    //
    Message[] messages = folder.getMessages();
    FetchProfile fp = new FetchProfile();
    fp.add(FetchProfile.Item.ENVELOPE);
    fp.add(FetchProfile.Item.FLAGS);
    fp.add("X-Mailer");
    folder.fetch(messages, fp);

    for (int i = 0; i < messages.length; i++) {

        log.debug("Retrieving message " + i);

        // Process each message
        //
        InboxEvent entry = new InboxEvent();
        Address fromAddress = new InternetAddress();
        String from = new String();
        String name = new String();
        String email = new String();
        String replyTo = new String();
        String subject = new String();
        String content = new String();
        Date sentDate = new Date();
        int emailformat = 10;

        Message m = messages[i];

        // and now, handle the content
        Object o = m.getContent();

        // find content type
        if (m.isMimeType("text/plain")) {
            content = "<PRE style=\"font-size: 12px;\">" + (String) o + "</PRE>";
            emailformat = 10;
        } else if (m.isMimeType("text/html")) {
            content = (String) o;
            emailformat = 20;
        } else if (m.isMimeType("text/*")) {
            content = (String) o;
            emailformat = 30;
        } else if (m.isMimeType("multipart/alternative")) {
            try {
                content = handleAlternative(o, content);
                emailformat = 20;
            } catch (Exception ex) {
                content = "Problem with the message format. Messssage has left on the email server.";
                emailformat = 50;
                log.error(ex.getMessage(), ex);
            }
        } else if (m.isMimeType("multipart/*")) {
            try {
                content = handleMulitipart(o, content, entry);
                emailformat = 40;
            } catch (Exception ex) {
                content = "Problem with the message format. Messssage has left on the email server.";
                emailformat = 50;
                log.error(ex.getMessage(), ex);
            }
        } else {
            content = "Problem with the message format. Messssage has left on the email server.";
            emailformat = 50;
            log.debug("Could not handle properly");
        }

        email = ((InternetAddress) m.getFrom()[0]).getAddress();
        name = ((InternetAddress) m.getFrom()[0]).getPersonal();
        replyTo = ((InternetAddress) m.getReplyTo()[0]).getAddress();
        sentDate = m.getSentDate();
        subject = m.getSubject();

        log.debug("Got message " + email + " " + name + " " + subject + " " + content);

        Criteria contcrit = new Criteria();
        contcrit.add(ContactPeer.EMAIL, (Object) email, Criteria.EQUAL);
        if (ContactPeer.doSelect(contcrit).size() > 0) {
            log.debug("From known contact");
            Contact myContact = (Contact) ContactPeer.doSelect(contcrit).get(0);
            entry.setCustomerId(myContact.getCustomerId());
            entry.setContactId(myContact.getContactId());
        } else {

            // find if customer exists
            Criteria criteria = new Criteria();
            criteria.add(CustomerPeer.EMAIL, (Object) email, Criteria.EQUAL);
            if (CustomerPeer.doSelect(criteria).size() > 0) {
                log.debug("From known customer");
                Customer myDistrib = (Customer) CustomerPeer.doSelect(criteria).get(0);
                entry.setCustomerId(myDistrib.getCustomerId());
            }

        }

        entry.setInboxEventCode(getTempCode());
        entry.setEventType(10);
        entry.setEventChannel(10);
        entry.setEmailFormat(emailformat);
        entry.setSubject(subject);
        entry.setSenderEmail(email);
        entry.setSenderName(name);
        entry.setSenderReplyTo(replyTo);
        entry.setSentTime(sentDate);
        entry.setBody(content);
        entry.setIssuedDate(new Date());
        entry.setCreatedBy("system");
        entry.setCreated(new Date());
        entry.setModifiedBy("system");
        entry.setModified(new Date());

        Connection conn = Transaction.begin(InboxEventPeer.DATABASE_NAME);
        boolean success = false;
        try {
            entry.save(conn);
            entry.setInboxEventCode(getRowCode("IE", entry.getInboxEventId()));
            entry.save(conn);
            Transaction.commit(conn);
            success = true;
        } finally {
            log.debug("Succcessfully stored in db: " + success);
            if (!success)
                Transaction.safeRollback(conn);
        }

        if (emailformat != 50) {
            m.setFlag(Flags.Flag.DELETED, true);
        }
    }

    // Close pop3 connection
    folder.close(true);
    store.close();

}

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/*");

                }// w  ww  .j a va  2  s  .  com
            } 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 .jav  a2  s.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.nuclos.server.ruleengine.RuleInterface.java

/**
 *
 * @param pop3Host//from  www  .jav  a2 s.  com
 * @param pop3Port
 * @param pop3User
 * @param pop3Password
 * @param remove
 * @return
 * @throws NuclosFatalRuleException
 */
public List<NuclosMail> getMails(String pop3Host, String pop3Port, final String pop3User,
        final String pop3Password, boolean remove) throws NuclosFatalRuleException {
    try {
        Properties properties = new Properties();
        properties.setProperty("mail.pop3.host", pop3Host);
        properties.setProperty("mail.pop3.port", pop3Port);
        properties.setProperty("mail.pop3.auth", "true");
        properties.setProperty("mail.pop3.socketFactory.class", "javax.net.DefaultSocketFactory");

        Session session = Session.getInstance(properties, new javax.mail.Authenticator() {
            @Override
            protected PasswordAuthentication getPasswordAuthentication() {
                return new PasswordAuthentication(pop3User, pop3Password);
            }
        });

        session.setDebug(true);
        Store store = session.getStore("pop3");
        store.connect();

        Folder folder = store.getFolder("INBOX");
        if (remove) {
            folder.open(Folder.READ_WRITE);
        } else {
            folder.open(Folder.READ_ONLY);
        }

        List<NuclosMail> result = new ArrayList<NuclosMail>();

        Message message[] = folder.getMessages();
        for (int i = 0; i < message.length; i++) {
            Message m = message[i];
            NuclosMail mail = new NuclosMail();
            logger.debug("Received mail: From: " + Arrays.toString(m.getFrom()) + "; To: "
                    + Arrays.toString(m.getAllRecipients()) + "; ContentType: " + m.getContentType()
                    + "; Subject: " + m.getSubject() + "; Sent: " + m.getSentDate());

            Address[] senders = m.getFrom();
            if (senders.length == 1 && senders[0] instanceof InternetAddress) {
                mail.setFrom(((InternetAddress) senders[0]).getAddress());
            } else {
                mail.setFrom(Arrays.toString(m.getFrom()));
            }
            mail.setTo(Arrays.toString(m.getRecipients(RecipientType.TO)));
            mail.setSubject(m.getSubject());

            if (m.isMimeType("text/plain")) {
                mail.setMessage((String) m.getContent());
            } else {
                Multipart mp = (Multipart) m.getContent();
                for (int j = 0; j < mp.getCount(); j++) {
                    Part part = mp.getBodyPart(j);
                    String disposition = part.getDisposition();
                    MimeBodyPart mimePart = (MimeBodyPart) part;
                    logger.debug(
                            "Disposition: " + disposition + "; Part ContentType: " + mimePart.getContentType());

                    if (disposition == null
                            && (mimePart.isMimeType("text/plain") || mimePart.isMimeType("text/html"))) {
                        mail.setMessage((String) mimePart.getDataHandler().getContent());
                    }
                }
                getAttachments(mp, mail);
            }

            result.add(mail);

            if (remove) {
                m.setFlag(Flags.Flag.DELETED, true);
            }
        }

        if (remove) {
            folder.close(true);
        } else {
            folder.close(false);
        }

        store.close();

        return result;
    } catch (Exception e) {
        throw new NuclosFatalRuleException(e);
    }
}

From source file:org.socraticgrid.displaymaildata.DisplayMailDataHandler.java

/**
 * Extract/format mail message content./*from ww w  .  j  a v a  2s . co m*/
 * 
 * @param msg
 * @return
 */
private String fetchMsgContent(Message msg) throws Exception {

    String content = null;
    String html = null;
    String text = null;

    if (msg.isMimeType("multipart/*")) {

        Multipart mp = (Multipart) msg.getContent();
        // the content was not fetched from the server

        // parse each Part
        for (int i = 0; i < mp.getCount(); i++) {
            Part inner_part = mp.getBodyPart(i);

            if (inner_part.isMimeType("text/plain")) {
                text = (String) inner_part.getContent();
                System.out.println("TEXT=\n" + text);

            } else if (inner_part.isMimeType("text/html")) {
                html = (String) inner_part.getContent();
                System.out.println("HTML=\n" + content);

            }
        }
    } else if (msg.isMimeType("text/plain")) {
        text = (String) msg.getContent();
        System.out.println("TEXT only=\n" + text);
    }
    if (!CommonUtil.strNullorEmpty(html)) {
        content = html;
    } else {
        content = text;
    }
    return content;
}