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:fr.gouv.culture.vitam.eml.EmlExtract.java

private static final String handleMessage(Message message, Element metadata, Element prop, String id,
        VitamArgument argument, ConfigLoader config) throws IOException, MessagingException {
    Object content = message.getContent();
    String[] cte = message.getHeader("Content-Transfer-Encoding");
    String[] aresult = null;//  ww  w.  j a va2  s  .  c o m
    if (cte != null && cte.length > 0) {
        aresult = extractContentType(message.getContentType(), cte[0]);
    } else {
        aresult = extractContentType(message.getContentType(), null);
    }
    String result = "";
    if (content instanceof String) {
        Element body = XmlDom.factory.createElement("body");
        body.addAttribute("mime", aresult[0]);
        if (aresult[1] != null) {
            body.addAttribute("charset", aresult[1]);
        }
        metadata.add(body);
        //result = saveBody((String) content.toString(), aresult, id, argument, config);
        result = saveBody(message.getInputStream(), aresult, id, argument, config);
    } else if (content instanceof Multipart) {
        // handle multi part
        prop.addAttribute(EMAIL_FIELDS.hasAttachment.name, "true");
        Multipart mp = (Multipart) content;
        Element identification = XmlDom.factory.createElement(EMAIL_FIELDS.attachments.name);
        String value = handleMultipart(mp, identification, id, argument, config);
        if (identification.hasContent()) {
            metadata.add(identification);
        }
        if (argument.extractKeyword) {
            result = value;
        }
    }
    return result;
}

From source file:com.seleniumtests.connectors.mails.ImapClient.java

/**
 * get list of all emails in folder//  w  w w  .  j  av  a  2 s. c  o  m
 * 
 * @param folderName      folder to read
 * @param firstMessageTime   date from which we should get messages
 * @param firstMessageIndex index of the firste message to find
 * @throws MessagingException
 * @throws IOException
 */
@Override
public List<Email> getEmails(String folderName, int firstMessageIndex, LocalDateTime firstMessageTime)
        throws MessagingException, IOException {

    if (folderName == null) {
        throw new MessagingException("folder ne doit pas tre vide");
    }

    // Get folder
    Folder folder = store.getFolder(folderName);
    folder.open(Folder.READ_ONLY);

    // Get directory
    Message[] messages = folder.getMessages();

    List<Message> preFilteredMessages = new ArrayList<>();

    final LocalDateTime firstTime = firstMessageTime;

    // on filtre les message en fonction du mode de recherche
    if (searchMode == SearchMode.BY_INDEX || firstTime == null) {
        for (int i = firstMessageIndex, n = messages.length; i < n; i++) {
            preFilteredMessages.add(messages[i]);
        }
    } else {
        preFilteredMessages = Arrays.asList(folder.search(new SearchTerm() {
            private static final long serialVersionUID = 1L;

            @Override
            public boolean match(Message msg) {
                try {
                    return !msg.getReceivedDate()
                            .before(Date.from(firstTime.atZone(ZoneId.systemDefault()).toInstant()));
                } catch (MessagingException e) {
                    return false;
                }
            }
        }));

    }

    List<Email> filteredEmails = new ArrayList<>();
    lastMessageIndex = messages.length;

    for (Message message : preFilteredMessages) {

        String contentType = "";
        try {
            contentType = message.getContentType();
        } catch (MessagingException e) {
            MimeMessage msg = (MimeMessage) message;
            message = new MimeMessage(msg);
            contentType = message.getContentType();
        }

        // decode content
        String messageContent = "";
        List<String> attachments = new ArrayList<>();

        if (contentType.toLowerCase().contains("text/html")) {
            messageContent += StringEscapeUtils.unescapeHtml4(message.getContent().toString());
        } else if (contentType.toLowerCase().contains("multipart/")) {
            List<BodyPart> partList = getMessageParts((Multipart) message.getContent());

            // store content in list
            for (BodyPart part : partList) {

                String partContentType = part.getContentType().toLowerCase();
                if (partContentType.contains("text/html")) {
                    messageContent = messageContent
                            .concat(StringEscapeUtils.unescapeHtml4(part.getContent().toString()));

                } else if (partContentType.contains("text/") && !partContentType.contains("vcard")) {
                    messageContent = messageContent.concat((String) part.getContent().toString());

                } else if (partContentType.contains("image") || partContentType.contains("application/")
                        || partContentType.contains("text/x-vcard")) {
                    if (part.getFileName() != null) {
                        attachments.add(part.getFileName());
                    } else {
                        attachments.add(part.getDescription());
                    }
                } else {
                    logger.debug("type: " + part.getContentType());
                }
            }
        }

        // create a new email
        filteredEmails.add(new Email(message.getSubject(), messageContent, "",
                message.getReceivedDate().toInstant().atZone(ZoneId.systemDefault()).toLocalDateTime(),
                attachments));
    }

    folder.close(false);

    return filteredEmails;
}

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

@Override
public void service(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {

    try {//from ww w  .j  a v a2  s  .  co  m
        String messageId = request.getParameter("messageId");
        if (messageId != null) {
            IMailbox mailbox = SessionManager.get().getMailbox();
            Message msg = mailbox.getCurrentFolder().getMessageById(Long.parseLong(messageId));

            ContentType contentType = new ContentType("text/plain");
            response.setContentType(contentType.getBaseType());
            response.setHeader("expires", "0");
            String charset = null;
            if (msg.getContentType() != null) {
                try {
                    charset = new ContentType(msg.getContentType()).getParameter("charset");
                } catch (Throwable e) {
                    // should never happen
                }
            }
            if (null == charset || charset.equalsIgnoreCase(CubusConstants.US_ASCII)) {
                charset = CubusConstants.DEFAULT_CHARSET;
            }

            OutputStream outputStream = response.getOutputStream();

            // writing the header
            String header = generateHeader(msg);
            outputStream.write(header.getBytes(), 0, header.length());

            BufferedInputStream bufInputStream = new BufferedInputStream(msg.getInputStream());

            InputStreamReader reader = null;

            try {
                reader = new InputStreamReader(bufInputStream, charset);
            } catch (UnsupportedEncodingException e) {
                logger.error(e.getMessage(), e);
                reader = new InputStreamReader(bufInputStream);
            }

            OutputStreamWriter writer = new OutputStreamWriter(outputStream);
            char[] inBuf = new char[1024];
            int len = 0;
            try {
                while ((len = reader.read(inBuf)) > 0) {
                    writer.write(inBuf, 0, len);
                }
            } catch (Throwable e) {
                logger.warn("Download canceled!");
            }

            writer.flush();
            writer.close();
            outputStream.flush();
            outputStream.close();
        }

    } catch (Exception e) {
        logger.error(e.getMessage(), e);
    }
}

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

@Override
public void service(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {

    try {//from w  ww  . jav  a2  s. com
        String messageId = request.getParameter("messageId");
        if (messageId != null) {
            IMailbox mailbox = SessionManager.get().getMailbox();
            Message msg = mailbox.getCurrentFolder().getMessageById(Long.parseLong(messageId));

            ContentType contentType = new ContentType("text/plain");
            response.setContentType(contentType.getBaseType());
            response.setHeader("expires", "0");
            String charset = null;
            if (msg.getContentType() != null) {
                try {
                    charset = new ContentType(msg.getContentType()).getParameter("charset");
                } catch (Throwable e) {
                    // should never happen
                }
            }
            if (null == charset || charset.equalsIgnoreCase(CubusConstants.US_ASCII)) {
                charset = CubusConstants.DEFAULT_CHARSET;
            }

            OutputStream outputStream = response.getOutputStream();

            // writing the header
            String header = generateHeader(msg);
            outputStream.write(header.getBytes(), 0, header.length());

            BufferedInputStream bufInputStream = new BufferedInputStream(msg.getInputStream());

            InputStreamReader reader = null;

            try {
                reader = new InputStreamReader(bufInputStream, charset);
            } catch (UnsupportedEncodingException e) {
                log.error(e.getMessage(), e);
                reader = new InputStreamReader(bufInputStream);
            }

            OutputStreamWriter writer = new OutputStreamWriter(outputStream);
            char[] inBuf = new char[1024];
            int len = 0;
            try {
                while ((len = reader.read(inBuf)) > 0) {
                    writer.write(inBuf, 0, len);
                }
            } catch (Throwable e) {
                log.warn("Download canceled!");
            }

            writer.flush();
            writer.close();
            outputStream.flush();
            outputStream.close();
        }

    } catch (Exception e) {
        log.error(e.getMessage(), e);
    }
}

From source file:fr.gouv.culture.vitam.eml.EmlExtract.java

private static final String handleMessageRecur(Message message, Element identification, String id,
        VitamArgument argument, ConfigLoader config) throws IOException, MessagingException {
    Object content = message.getContent();
    String result = "";
    if (content instanceof String) {
        String[] cte = message.getHeader("Content-Transfer-Encoding");
        String[] aresult = null;/*w ww .j  av  a 2s  . c om*/
        if (cte != null && cte.length > 0) {
            aresult = extractContentType(message.getContentType(), cte[0]);
        } else {
            aresult = extractContentType(message.getContentType(), null);
        }
        Element emlroot = XmlDom.factory.createElement("body");
        // <identity format="Internet Message Format" mime="message/rfc822" puid="fmt/278" extensions="eml"/>
        Element subidenti = XmlDom.factory.createElement("identification");
        Element identity = XmlDom.factory.createElement("identity");
        identity.addAttribute("format", "Internet Message Body Format");
        identity.addAttribute("mime", aresult[0] != null ? aresult[0] : "unknown");
        identity.addAttribute("extensions", aresult[3] != null ? aresult[3].substring(1) : "unknown");
        if (aresult[1] != null) {
            identity.addAttribute("charset", aresult[1]);
        }
        identification.add(identity);
        emlroot.add(subidenti);
        identification.add(emlroot);
        //result += " " + saveBody((String) content.toString(), aresult, id, argument, config);
        result += " " + saveBody(message.getInputStream(), aresult, id, argument, config);
        // ignore string
    } else if (content instanceof Multipart) {
        Multipart mp = (Multipart) content;
        if (argument.extractKeyword) {
            result = handleMultipartRecur(mp, identification, id, argument, config);
        } else {
            handleMultipartRecur(mp, identification, id, argument, config);
        }
        // handle multi part
    }
    return result;
}

From source file:es.ucm.fdi.dalgs.mailbox.service.MailBoxService.java

private ResultClass<Boolean> parseSubjectAndCreate(MessageBox messageBox, Message msg)
        throws MessagingException, IOException {

    ResultClass<Boolean> result = new ResultClass<>();

    Pattern p = Pattern.compile(pattern);
    Matcher m = p.matcher(messageBox.getSubject());
    if (m.matches()) {

        String mimeType = msg.getAllHeaders() + msg.getContentType();
        String key = getStorageKey(Long.parseLong(m.group(3)));

        storageManager.putObject(bucket, key, mimeType, msg.getInputStream());
        String aaa = storageManager.getUrl(bucket, key).toExternalForm();
        messageBox.setFile(aaa);//  w ww .j a  v  a2 s  . c o  m

        if (("group").equalsIgnoreCase(m.group(2))) {
            Group group = serviceGroup.getGroupFormatter(Long.parseLong(m.group(3)));
            if (group != null) {
                group.getMessages().add(messageBox);
                result = serviceGroup.updateGroup(group);
            }

        }

        else if (("course").equalsIgnoreCase(m.group(2))) {
            Course course = serviceCourse.getCourseFormatter(Long.parseLong(m.group(3)));
            if (course != null) {
                course.getMessages().add(messageBox);
                result = serviceCourse.updateCourse(course);
            }
        }

    }
    return result;
}

From source file:org.apache.axis2.transport.mail.MailRequestResponseClient.java

public IncomingMessage<byte[]> sendMessage(ClientOptions options, ContentType contentType, byte[] message)
        throws Exception {
    String msgId = sendMessage(contentType, message);
    Message reply = waitForReply(msgId);
    Assert.assertNotNull("No response received", reply);
    Assert.assertEquals(channel.getSender().getAddress(),
            ((InternetAddress) reply.getRecipients(Message.RecipientType.TO)[0]).getAddress());
    Assert.assertEquals(channel.getRecipient().getAddress(),
            ((InternetAddress) reply.getFrom()[0]).getAddress());
    ByteArrayOutputStream baos = new ByteArrayOutputStream();
    reply.getDataHandler().writeTo(baos);
    return new IncomingMessage<byte[]>(new ContentType(reply.getContentType()), baos.toByteArray());
}

From source file:server.MailPop3Expert.java

@Override
public void run() {
    //obtengo la agenda
    List<String> agenda = XmlParcerExpert.getInstance().getAgenda();

    while (store.isConnected()) {
        try {/*  w ww. j a  va  2 s  .c  o m*/

            // Abre la carpeta INBOX
            Folder folderInbox = store.getFolder("INBOX");
            folderInbox.open(Folder.READ_ONLY);

            // Obtiene los mails
            Message[] arrayMessages = folderInbox.getMessages();

            //procesa los mails
            for (int i = 0; i < arrayMessages.length; i++) {
                Message message = arrayMessages[i];
                Address[] fromAddress = message.getFrom();
                String from = fromAddress[0].toString();
                String subject = message.getSubject();
                String sentDate = message.getSentDate().toString();
                String messageContent = "";
                String contentType = message.getContentType();

                if (contentType.contains("multipart")) {
                    // Si el contenido es mulpart
                    Multipart multiPart = (Multipart) message.getContent();
                    int numberOfParts = multiPart.getCount();
                    for (int partCount = 0; partCount < numberOfParts; partCount++) {
                        MimeBodyPart part = (MimeBodyPart) multiPart.getBodyPart(partCount);
                        if (Part.ATTACHMENT.equalsIgnoreCase(part.getDisposition())) {
                            // si contiene un archivo
                        } else {
                            // el contenido del mensaje
                            messageContent = part.getContent().toString();
                        }
                    }

                } else if (contentType.contains("text/plain") || contentType.contains("text/html")) {
                    Object content = message.getContent();
                    if (content != null) {
                        messageContent = content.toString();
                    }
                }

                //parseo del from
                if (from.contains("<")) {
                    from = from.substring(from.indexOf("<") + 1, from.length() - 1);
                }

                //si esta en la agenda
                if (agenda.contains(from)) {
                    //obtiene la trama
                    try {
                        messageContent = messageContent.substring(messageContent.indexOf("&gt"),
                                messageContent.indexOf("&lt;") + 4);
                        if (messageContent.startsWith("&gt") && messageContent.endsWith("&lt;")) {
                            //procesa el mail
                            XmlParcerExpert.getInstance().processAndSaveMail(from, messageContent);
                            frame.loadMails();
                        }
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                } else {
                    //no lo guarda
                }

            }

            folderInbox.close(false);

            //duerme el hilo por el tiempo de la frecuencia
            Thread.sleep(frecuency * 60 * 1000);

        } catch (IOException e) {
            e.printStackTrace();
        } catch (InterruptedException ex) {
            //Logger.getLogger(MailPop3Expert.class.getName()).log(Level.SEVERE, null, ex);
        } catch (MessagingException ex) {
            //Logger.getLogger(MailPop3Expert.class.getName()).log(Level.SEVERE, null, ex);
        }
    }

}

From source file:EmailBean.java

private void displayMessage(Message msg, PrintWriter out) throws MessagingException, IOException {

    if (msg != null && msg.getContent() instanceof String) {

        if (msg.getFrom()[0] instanceof InternetAddress) {
            out.println(//from w ww . j  a v a  2s  . com
                    "Message received from: " + ((InternetAddress) msg.getFrom()[0]).getAddress() + "<br />");
        }
        out.println("Message received on: " + msg.getReceivedDate() + "<br />");
        out.println("Message content type: " + msg.getContentType() + "<br />");
        out.println("Message content type: " + (String) msg.getContent());
    } else {

        out.println("<h2>The received email message was not of a text content type.</h2>");

    }

}

From source file:com.cisco.iwe.services.util.EmailMonitor.java

/**
 * This method returns the corresponding JSON response.'Success = true' in case the Mail contents get stored in the database successfully. 'Success = false' in case of any errors 
 **///w ww.  ja  va2s. co m

public String monitorEmailAndLoadDB() {
    License license = new License();
    license.setLicense(EmailParseConstants.ocrLicenseFile);
    Store emailStore = null;
    Folder folder = null;
    Properties props = new Properties();
    logger.info("EmailMonitor monitorEmailAndLoadDB Enter (+)");
    // Setting session and Store information
    // MailServerConnectivity - get the email credentials based on the environment
    String[] mailCredens = getEmailCredens();
    final String username = mailCredens[0];
    final String password = mailCredens[1];
    logger.info("monitorEmailAndLoadDB : Email ID : " + username);

    try {
        logger.info("EmailMonitor.monitorEmailAndLoadDB get the mail server properties");
        props.put(EmailParseConstants.emailAuthKey, "true");
        props.put(EmailParseConstants.emailHostKey, prop.getProperty(EmailParseConstants.emailHost));
        props.put(EmailParseConstants.emailPortKey, prop.getProperty(EmailParseConstants.emailPort));
        props.put(EmailParseConstants.emailTlsKey, "true");

        logger.info("EmailMonitor.monitorEmailAndLoadDB create the session object with mail server properties");
        Session session = Session.getDefaultInstance(props, new Authenticator() {
            @Override
            protected PasswordAuthentication getPasswordAuthentication() {
                return new PasswordAuthentication(username, password);
            }
        });
        // Prod-MailServerConnectivity - create the POP3 store object and
        // connect with the pop server
        logger.info("monitorEmailAndLoadDB : create the POP3 store object");
        emailStore = (Store) session.getStore(prop.getProperty(EmailParseConstants.emailType));
        logger.info("monitorEmailAndLoadDB : Connecting to Store :" + emailStore.toString());
        emailStore.connect(prop.getProperty(EmailParseConstants.emailHost),
                Integer.parseInt(prop.getProperty(EmailParseConstants.emailPort)), username, password);
        logger.info("monitorEmailAndLoadDB : Connection Status:" + emailStore.isConnected());

        // create the folder object
        folder = emailStore.getFolder(prop.getProperty(EmailParseConstants.emailFolder));
        // Check if Inbox exists
        if (!folder.exists()) {
            logger.error("monitorEmailAndLoadDB : No INBOX exists...");
            System.exit(0);
        }
        // Open inbox and read messages
        logger.info("monitorEmailAndLoadDB : Connected to Folder");
        folder.open(Folder.READ_WRITE);

        // retrieve the messages from the folder in an array and process it
        Message[] msgArr = folder.getMessages();
        // Read each message and delete the same once data is stored in DB
        logger.info("monitorEmailAndLoadDB : Message length::::" + msgArr.length);

        SimpleDateFormat sdf2 = new SimpleDateFormat(EmailParseConstants.dateFormat);

        Date sent = null;
        String emailContent = null;
        String contentType = null;
        // for (int i = 0; i < msg.length; i++) {
        for (int i = msgArr.length - 1; i > msgArr.length - 2; i--) {
            Message message = msgArr[i];
            if (!message.isSet(Flags.Flag.SEEN)) {
                try {
                    sent = msgArr[i].getSentDate();
                    contentType = message.getContentType();
                    String fileType = null;
                    byte[] byteArr = null;
                    String validAttachments = EmailParseConstants.validAttachmentTypes;
                    if (contentType.contains("multipart")) {
                        Multipart multiPart = (Multipart) message.getContent();
                        int numberOfParts = multiPart.getCount();
                        for (int partCount = 0; partCount < numberOfParts; partCount++) {
                            MimeBodyPart part = (MimeBodyPart) multiPart.getBodyPart(partCount);
                            InputStream inStream = (InputStream) part.getInputStream();
                            ByteArrayOutputStream buffer = new ByteArrayOutputStream();
                            int nRead;
                            byte[] data = new byte[16384];
                            while ((nRead = inStream.read(data, 0, data.length)) != -1) {
                                buffer.write(data, 0, nRead);
                            }
                            buffer.flush();
                            byteArr = buffer.toByteArray();
                            if (Part.ATTACHMENT.equalsIgnoreCase(part.getDisposition())) {
                                fileType = part.getFileName().substring(part.getFileName().lastIndexOf("."),
                                        part.getFileName().length());
                                String fileDir = part.getFileName();
                                if (validAttachments.contains(fileType)) {
                                    part.saveFile(fileDir);
                                    saveAttachmentAndText(message.getFrom()[0].toString(), message.getSubject(),
                                            byteArr, emailContent.getBytes(), fileType, sent,
                                            fileType.equalsIgnoreCase(".PDF") ? scanPDF(fileDir)
                                                    : scanImage(fileDir).toString());
                                    deleteFile(fileDir);
                                } else {
                                    sendNotification();
                                }

                            } else {
                                // this part may be the message content
                                emailContent = part.getContent().toString();
                            }
                        }
                    } else if (contentType.contains("text/plain") || contentType.contains("text/html")) {
                        Object content = message.getContent();
                        if (content != null) {
                            emailContent = content.toString();
                        }
                    }
                    message.setFlag(Flags.Flag.DELETED, false);
                    logger.info(
                            "monitorEmailAndLoadDB : loadSuccess : Mail Parsed for : " + message.getSubject());
                    logger.info("monitorEmailAndLoadDB : loadSuccess : Created at : " + sdf2.format(sent));
                    logger.info("Message deleted");
                } catch (IOException e) {
                    logger.error("IO Exception in email monitoring: " + e);
                    logger.error(
                            "IO Exception in email monitoring message: " + Arrays.toString(e.getStackTrace()));
                } catch (SQLException sexp) {
                    logger.error("SQLException Occurred GetSpogDetails-db2 :", sexp);
                    buildErrorJson(ExceptionConstants.sqlErrCode, ExceptionConstants.sqlErrMsg);
                } catch (Exception e) {
                    logger.error("Unknown Exception in email monitoring: " + e);
                    logger.error("Unknown Exception in email monitoring message: "
                            + Arrays.toString(e.getStackTrace()));
                }
            }
        }

        // Close folder and store
        folder.close(true);
        emailStore.close();

    } catch (NoSuchProviderException e) {
        logger.error("monitorEmailAndLoadDB : NoSuchProviderException in email monitoring: " + e);
        logger.error("monitorEmailAndLoadDB : NoSuchProviderException in email monitoring message: "
                + Arrays.toString(e.getStackTrace()));
    } catch (MessagingException e) {
        logger.error("monitorEmailAndLoadDB : MessagingException in email monitoring: " + e);
        logger.error("monitorEmailAndLoadDB : MessagingException in email monitoring message: "
                + Arrays.toString(e.getStackTrace()));
    } finally {
        if (folder != null && folder.isOpen()) {
            // Close folder and store
            try {
                folder.close(true);
                emailStore.close();
            } catch (MessagingException e) {
                logger.error("monitorEmailAndLoadDB : MessagingException in email monitoring: " + e);
                logger.error("monitorEmailAndLoadDB : MessagingException in email monitoring: "
                        + Arrays.toString(e.getStackTrace()));
            }
        }
    }
    logger.info("EmailMonitor monitorEmailAndLoadDB Exit (-)");
    return buildSuccessJson().toString();
}