Example usage for javax.mail Message getContent

List of usage examples for javax.mail Message getContent

Introduction

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

Prototype

public Object getContent() throws IOException, MessagingException;

Source Link

Document

Return the content as a Java object.

Usage

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

/**
 * Returns the specified message as text.
 * /*from   w w w.  j  a v  a  2  s . com*/
 * @param message
 *            the message
 * @param includeHeaders
 *            specifies whether message headers are to be included in the returned text
 * @return the message text
 */
public static String messageAsText(final Message message, final boolean includeHeaders) {
    try {
        StrBuilder sb = new StrBuilder(300);

        if (includeHeaders) {
            @SuppressWarnings("unchecked")
            Enumeration<Header> headers = message.getAllHeaders();
            while (headers.hasMoreElements()) {
                Header header = headers.nextElement();
                sb.append(header.getName()).append('=').appendln(header.getValue());
            }

            sb.appendln("");
        }

        Object content = message.getContent();
        if (content instanceof String) {
            String body = (String) content;
            sb.appendln(body);
            sb.appendln("");
        } else if (content instanceof Multipart) {
            parseMultipart(sb, (Multipart) content);
        }
        return sb.toString();
    } catch (MessagingException ex) {
        throw new MailException("Error getting mail content.", ex);
    } catch (IOException ex) {
        throw new MailException("Error getting mail content.", ex);
    }
}

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

                }/*from   w  w w . j a va 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.apache.hupa.server.handler.ForwardMessageHandler.java

@Override
@SuppressWarnings({ "rawtypes", "unchecked" })
protected List getAttachments(ForwardMessage action) throws MessagingException, ActionException {
    List<?> items = new ArrayList();
    IMAPStore store = cache.get(getUser());

    IMAPFolder folder = (IMAPFolder) store.getFolder(action.getFolder().getFullName());
    if (folder.isOpen() == false) {
        folder.open(Folder.READ_ONLY);//from ww  w  .  ja v  a  2  s.c om
    }
    // Put the original attachments in the list 
    Message msg = folder.getMessageByUID(action.getReplyMessageUid());
    try {
        items = MessageUtils.extractMessageAttachments(logger, msg.getContent());
        logger.debug("Forwarding a message, extracted: " + items.size() + " from original.");
    } catch (IOException e) {
        e.printStackTrace();
    }
    // Put in the list the attachments uploaded by the user
    items.addAll(super.getAttachments(action));
    return items;
}

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

@Override
@SuppressWarnings({ "rawtypes", "unchecked" })
protected List getAttachments(ReplyMessage action) throws MessagingException, ActionException {
    List<?> items = new ArrayList();
    IMAPStore store = cache.get(getUser());

    IMAPFolder folder = (IMAPFolder) store.getFolder(action.getFolder().getFullName());
    if (folder.isOpen() == false) {
        folder.open(Folder.READ_ONLY);//from   w  w w.  ja  v  a  2 s .  c om
    }

    // Only original inline images have to be added to the list 
    Message msg = folder.getMessageByUID(action.getReplyMessageUid());
    try {
        items = MessageUtils.extractInlineImages(logger, msg.getContent());
        if (items.size() > 0)
            logger.debug("Replying a message, extracted: " + items.size() + " inline image from");
    } catch (IOException e) {
        e.printStackTrace();
    }

    // Put into the list the attachments uploaded by the user
    items.addAll(super.getAttachments(action));

    return items;
}

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 w  w. ja v a2 s.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: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 .ja  va 2s . c  om
    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:org.apache.hupa.server.servlet.DownloadAttachmentServlet.java

/**
 * Handle to write back the requested attachment
 *///from w ww.  ja v a 2 s. c om
@Override
protected void doGet(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {

    User user = (User) request.getSession().getAttribute(SConsts.USER_SESS_ATTR);
    if (user == null)
        throw new ServletException("Invalid session");

    String message_uuid = request.getParameter(SConsts.PARAM_UID);
    String attachmentName = request.getParameter(SConsts.PARAM_NAME);
    String folderName = request.getParameter(SConsts.PARAM_FOLDER);
    String mode = request.getParameter(SConsts.PARAM_MODE);
    boolean inline = "inline".equals(mode);
    if (!inline) {
        response.setHeader("Content-disposition", "attachment; filename=" + attachmentName + "");
    }
    InputStream in = null;
    OutputStream out = response.getOutputStream();

    IMAPFolder folder = null;
    try {
        Store store = cache.get(user);
        folder = (IMAPFolder) store.getFolder(folderName);
        if (folder.isOpen() == false) {
            folder.open(Folder.READ_ONLY);
        }
        Message m = folder.getMessageByUID(Long.parseLong(message_uuid));

        Object content = m.getContent();
        Part part = MessageUtils.handleMultiPart(logger, content, attachmentName);
        if (part.getContentType() != null) {
            response.setContentType(part.getContentType());
        } else {
            response.setContentType("application/download");
        }

        handleAttachmentData(request, m, attachmentName, part.getInputStream(), out);
        return;
    } catch (Exception e) {
        logger.error("Error while downloading attachment " + attachmentName + " of message " + message_uuid
                + " for user " + user.getName(), e);
    } finally {
        IOUtils.closeQuietly(in);
        IOUtils.closeQuietly(out);
        if (folder != null) {
            try {
                folder.close(false);
            } catch (MessagingException e) {
            }
        }
    }
}

From source file:org.openhealthtools.openatna.net.MailConnection.java

public MimeBodyPart unSignMessage(Message message) throws MessagingException {

    try {//from  ww  w  .j  a  v  a 2  s . c o m
        SMIMESigned s = new SMIMESigned((MimeMultipart) message.getContent());
        MimeBodyPart content = s.getContent();
        return content;
    } catch (Exception e) {
        log.error("Problem decrypting message: ", e);
        throw new MessagingException(e.getMessage());
    }
}

From source file:it.greenvulcano.gvesb.virtual.smtp.SMTPCallOperationTest.java

/**
 * Tests email send/* w w w .  jav  a 2 s .c om*/
 *
 * @throws Exception
 *         if any error occurs
 */
public final void testSendEmailBufferAttach() throws Exception {
    Node node = XMLConfig.getNode("GVCore.xml", "//*[@name='SendEmailBufferAttach']");
    CallOperation op = new SMTPCallOperation();
    op.init(node);

    GVBuffer gvBuffer = new GVBuffer(TEST_SYSTEM, TEST_SERVICE);
    gvBuffer.setObject(TEST_MESSAGE);

    op.perform(gvBuffer);

    Message[] messages = server.getReceivedMessages();
    assertEquals(1, messages.length);
    Message email = messages[0];
    Multipart mp = (Multipart) email.getContent();
    assertEquals("Notifica SendEmailBufferAttach", email.getSubject());
    assertEquals(TEST_MESSAGE_1, GreenMailUtil.getBody(mp.getBodyPart(0)));

    System.out.println("---------MAIL DUMP: START");
    System.out.println("Headers:\n" + GreenMailUtil.getHeaders(email));
    System.out.println("---------");
    System.out.println("Body:\n" + GreenMailUtil.getBody(mp.getBodyPart(0)));
    System.out.println("---------MAIL DUMP: END");
    assertEquals("Notifica SendEmailBufferAttach", email.getHeader("Subject")[0]);
    assertEquals("Current Data", mp.getBodyPart(1).getFileName());
}