Example usage for javax.mail.internet MimeMessage getContent

List of usage examples for javax.mail.internet MimeMessage getContent

Introduction

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

Prototype

@Override
public Object getContent() throws IOException, MessagingException 

Source Link

Document

Return the content as a Java object.

Usage

From source file:org.alfresco.repo.imap.ImapMessageTest.java

public void dontTestMessageCache() throws Exception {

    // Create messages
    NodeRef contentNode = findNode(companyHomePathInStore + TEST_FILE);
    UserTransaction txn = transactionService.getUserTransaction();
    txn.begin();//  w w w . j a va2 s .  c  o  m

    // Create messages more than cache capacity
    for (int i = 0; i < 51; i++) {
        FileInfo fi = fileFolderService.create(nodeService.getParentAssocs(contentNode).get(0).getParentRef(),
                "test" + i, ContentModel.TYPE_CONTENT);
        ContentWriter writer = fileFolderService.getWriter(fi.getNodeRef());
        writer.putContent("test");
    }

    txn.commit();

    // Reload folder
    folder.close(false);
    folder = (IMAPFolder) store.getFolder(TEST_FOLDER);
    folder.open(Folder.READ_ONLY);

    // Read all messages
    for (int i = 1; i < 51; i++) {
        // Get test message UID
        final Long uid = getMessageUid(folder, i);
        // Get Message size
        final int count = getMessageSize(folder, uid);

        // Get first part
        BODY body = getMessageBodyPart(folder, uid, 0, count - 100);
        // Read second message part
        BODY bodyRest = getMessageBodyPart(folder, uid, count - 100, 100);

        // Creating and parsing message from 2 parts
        MimeMessage message = new MimeMessage(Session.getDefaultInstance(new Properties()),
                new SequenceInputStream(new BufferedInputStream(body.getByteArrayInputStream()),
                        new BufferedInputStream(bodyRest.getByteArrayInputStream())));

        // Reading first part - should be successful
        MimeMultipart content = (MimeMultipart) message.getContent();
        assertNotNull(content.getBodyPart(0).getContent());
        assertNotNull(content.getBodyPart(1).getContent());
    }
}

From source file:org.alfresco.repo.imap.ImapMessageTest.java

public void testUnmodifiedMessage() throws Exception {
    // Get test message UID
    final Long uid = getMessageUid(folder, 1);
    // Get Message size
    final int count = getMessageSize(folder, uid);

    // Make multiple message reading
    for (int i = 0; i < 100; i++) {
        // Get random offset
        int n = (int) ((int) 100 * Math.random());

        // Get first part
        BODY body = getMessageBodyPart(folder, uid, 0, count - n);
        // Read second message part
        BODY bodyRest = getMessageBodyPart(folder, uid, count - n, n);

        // Creating and parsing message from 2 parts
        MimeMessage message = new MimeMessage(Session.getDefaultInstance(new Properties()),
                new SequenceInputStream(new BufferedInputStream(body.getByteArrayInputStream()),
                        new BufferedInputStream(bodyRest.getByteArrayInputStream())));

        MimeMultipart content = (MimeMultipart) message.getContent();
        // Reading first part - should be successful
        assertNotNull(content.getBodyPart(0).getContent());
        // Reading second part - should be successful
        assertNotNull(content.getBodyPart(1).getContent());
    }/*  w ww. j av a  2  s. c  o m*/
}

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

public int checkInbox(int mode) throws MessagingException, IOException {
    int numMessages = 0;

    if (mode == 0) {
        return 0;
    }/*from w w  w  . jav  a 2 s.c  o  m*/

    boolean show = (mode & SHOW_MESSAGES) > 0;
    boolean clear = (mode & CLEAR_MESSAGES) > 0;
    String action = (show ? "Show" : "") + ((show && clear) ? " and " : "") + (clear ? "Clear" : "");

    log.info(action + " INBOX for " + from);

    Store store = session.getStore();

    store.connect();

    Folder root = store.getDefaultFolder();
    Folder inbox = root.getFolder("inbox");

    inbox.open(Folder.READ_WRITE);

    Message[] msgs = inbox.getMessages();

    numMessages = msgs.length;

    if ((msgs.length == 0) && show) {
        log.info("No messages in inbox");
    }

    for (int i = 0; i < msgs.length; i++) {
        MimeMessage msg = (MimeMessage) msgs[i];

        if (show) {
            log.info("    From: " + msg.getFrom()[0]);
            log.info(" Subject: " + msg.getSubject());
            log.info(" Content: " + msg.getContent());
        }

        if (clear) {
            msg.setFlag(Flags.Flag.DELETED, true);
        }
    }

    inbox.close(true);
    store.close();

    return numMessages;
}

From source file:org.apache.axis2.transport.mail.server.MailSorter.java

public void processMail(ConfigurationContext confContext, MimeMessage mimeMessage) {
    // create an Axis server
    AxisEngine engine = new AxisEngine(confContext);
    MessageContext msgContext = null;

    // create and initialize a message context
    try {/* www.  ja va2s.  c o m*/
        msgContext = confContext.createMessageContext();
        msgContext.setTransportIn(
                confContext.getAxisConfiguration().getTransportIn(org.apache.axis2.Constants.TRANSPORT_MAIL));
        msgContext.setTransportOut(
                confContext.getAxisConfiguration().getTransportOut(org.apache.axis2.Constants.TRANSPORT_MAIL));

        msgContext.setServerSide(true);
        msgContext.setProperty(Constants.CONTENT_TYPE, mimeMessage.getContentType());
        msgContext.setProperty(org.apache.axis2.Constants.Configuration.CHARACTER_SET_ENCODING,
                mimeMessage.getEncoding());
        String soapAction = getMailHeader(Constants.HEADER_SOAP_ACTION, mimeMessage);
        if (soapAction == null) {
            soapAction = mimeMessage.getSubject();
        }

        msgContext.setSoapAction(soapAction);
        msgContext.setIncomingTransportName(org.apache.axis2.Constants.TRANSPORT_MAIL);

        String serviceURL = mimeMessage.getSubject();

        if (serviceURL == null) {
            serviceURL = "";
        }

        String replyTo = ((InternetAddress) mimeMessage.getReplyTo()[0]).getAddress();

        if (replyTo != null) {
            msgContext.setReplyTo(new EndpointReference(replyTo));
        }

        String recepainets = ((InternetAddress) mimeMessage.getAllRecipients()[0]).getAddress();

        if (recepainets != null) {
            msgContext.setTo(new EndpointReference(recepainets + "/" + serviceURL));
        }

        // add the SOAPEnvelope
        String message = mimeMessage.getContent().toString();

        log.info("message[" + message + "]");

        ByteArrayInputStream bais = new ByteArrayInputStream(message.getBytes());
        String soapNamespaceURI = "";

        if (mimeMessage.getContentType().indexOf(SOAP12Constants.SOAP_12_CONTENT_TYPE) > -1) {
            soapNamespaceURI = SOAP12Constants.SOAP_ENVELOPE_NAMESPACE_URI;
        } else if (mimeMessage.getContentType().indexOf(SOAP11Constants.SOAP_11_CONTENT_TYPE) > -1) {
            soapNamespaceURI = SOAP11Constants.SOAP_ENVELOPE_NAMESPACE_URI;
        }

        StAXBuilder builder = BuilderUtil.getSOAPBuilder(bais, soapNamespaceURI);

        SOAPEnvelope envelope = (SOAPEnvelope) builder.getDocumentElement();

        msgContext.setEnvelope(envelope);

        AxisEngine.receive(msgContext);
    } catch (Exception e) {
        try {
            if (msgContext != null) {
                MessageContext faultContext = MessageContextBuilder.createFaultMessageContext(msgContext, e);

                engine.sendFault(faultContext);
            }
        } catch (Exception e1) {
            log.error(e.getMessage(), e);
        }
    }
}

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

private MessageContext createMessageContextToMailWorker(MimeMessage msg) throws Exception {
    Object content = msg.getContent();
    if (!(content instanceof Multipart)) {
        return null;
    }//  w  w  w  . j av  a 2 s .c om
    MessageContext msgContext = null;
    TransportInDescription transportIn = configurationContext.getAxisConfiguration()
            .getTransportIn(org.apache.axis2.Constants.TRANSPORT_MAIL);
    TransportOutDescription transportOut = configurationContext.getAxisConfiguration()
            .getTransportOut(org.apache.axis2.Constants.TRANSPORT_MAIL);
    if ((transportIn != null) && (transportOut != null)) {
        // create Message Context
        msgContext = configurationContext.createMessageContext();
        msgContext.setTransportIn(transportIn);
        msgContext.setTransportOut(transportOut);
        msgContext.setServerSide(true);
        msgContext.setProperty(org.apache.axis2.transport.mail.Constants.CONTENT_TYPE, msg.getContentType());
        msgContext.setIncomingTransportName(org.apache.axis2.Constants.TRANSPORT_MAIL);

        MailBasedOutTransportInfo transportInfo = new MailBasedOutTransportInfo();
        Address[] mimefroms = msg.getFrom();
        if (mimefroms != null && mimefroms.length > 0) {
            EndpointReference fromEPR = new EndpointReference(
                    org.apache.axis2.transport.mail.Constants.MAILTO + ":" + msg.getFrom()[0].toString());
            transportInfo.setFrom(fromEPR);
        } else {
            String returnPath = getMailHeader(msg, org.apache.axis2.transport.mail.Constants.RETURN_PATH);
            returnPath = parseHeaderForLessThan(returnPath);
            if (returnPath != null) {
                EndpointReference fromEPR = new EndpointReference(
                        org.apache.axis2.transport.mail.Constants.MAILTO + ":" + returnPath);
                transportInfo.setFrom(fromEPR);
            }
        }

        // Save Message-Id to set as In-Reply-To on reply
        String smtpMessageId = msg.getMessageID();
        if (smtpMessageId != null) {
            transportInfo.setInReplyTo(smtpMessageId);
        }
        String inReplyTo = getMailHeader(msg, org.apache.axis2.transport.mail.Constants.IN_REPLY_TO);
        if (inReplyTo != null) {
            transportInfo.setInReplyTo(inReplyTo);
        }
        msgContext.setProperty(org.apache.axis2.Constants.OUT_TRANSPORT_INFO, transportInfo);

        buildSOAPEnvelope(msg, msgContext);
        if (!fillMessageContextFromAvaiableData(msgContext, inReplyTo)) {
            return null;
        }
    }
    return msgContext;
}

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

private void buildSOAPEnvelope(MimeMessage msg, MessageContext msgContext) throws AxisFault {
    //TODO we assume for the time being that there is only one attachement and this attachement contains  the soap evelope
    try {/* w  ww .  ja  v a 2  s. c  o  m*/
        Multipart mp = (Multipart) msg.getContent();
        if (mp != null) {
            for (int i = 0, n = mp.getCount(); i < n; i++) {
                Part part = mp.getBodyPart(i);

                String disposition = part.getDisposition();

                if (disposition != null && disposition.equalsIgnoreCase(Part.ATTACHMENT)) {
                    String soapAction;

                    /* Set the Charactorset Encoding */
                    String contentType = part.getContentType();
                    String charSetEncoding = BuilderUtil.getCharSetEncoding(contentType);
                    if (charSetEncoding != null) {
                        msgContext.setProperty(org.apache.axis2.Constants.Configuration.CHARACTER_SET_ENCODING,
                                charSetEncoding);
                    } else {
                        msgContext.setProperty(org.apache.axis2.Constants.Configuration.CHARACTER_SET_ENCODING,
                                MessageContext.DEFAULT_CHAR_SET_ENCODING);
                    }

                    /* SOAP Action */
                    soapAction = getMailHeaderFromPart(part,
                            org.apache.axis2.transport.mail.Constants.HEADER_SOAP_ACTION);
                    msgContext.setSoapAction(soapAction);

                    String contentDescription = getMailHeaderFromPart(part, "Content-Description");

                    /* As an input stream - using the getInputStream() method.
                    Any mail-specific encodings are decoded before this stream is returned.*/
                    if (contentDescription != null) {
                        msgContext.setTo(new EndpointReference(contentDescription));
                    }

                    if (contentType.indexOf(SOAP12Constants.SOAP_12_CONTENT_TYPE) > -1) {
                        TransportUtils.processContentTypeForAction(contentType, msgContext);
                    } else {
                        // According to the mail sepec, mail transport should support only
                        // application/soap+xml;
                        String message = "According to the mail sepec, mail transport "
                                + "should support only application/soap+xml";
                        log.error(message);
                        throw new AxisFault(message);
                    }

                    String cte = getMailHeaderFromPart(part, "Content-Transfer-Encoding");
                    if (!(cte != null && cte.equalsIgnoreCase("base64"))) {
                        String message = "Processing of Content-Transfer-Encoding faild.";
                        log.error(message);
                        throw new AxisFault(message);
                    }
                    InputStream inputStream = part.getInputStream();
                    SOAPEnvelope envelope = TransportUtils.createSOAPMessage(msgContext, inputStream,
                            contentType);
                    msgContext.setEnvelope(envelope);
                }
            }

        }
    } catch (IOException e) {
        throw new AxisFault(e.getMessage(), e);
    } catch (MessagingException e) {
        throw new AxisFault(e.getMessage(), e);
    } catch (XMLStreamException e) {
        throw new AxisFault(e.getMessage(), e);
    }
}

From source file:org.apache.camel.component.mail.MailBinding.java

/**
 * Extracts the body from the Mail message
 */// w ww .  j  ava 2 s.c om
public Object extractBodyFromMail(Exchange exchange, MailMessage mailMessage) {
    Message message = mailMessage.getMessage();
    try {
        return message.getContent();
    } catch (Exception e) {
        // try to fix message in case it has an unsupported encoding in the Content-Type header
        UnsupportedEncodingException uee = ObjectHelper.getException(UnsupportedEncodingException.class, e);
        if (uee != null) {
            LOG.debug("Unsupported encoding detected: " + uee.getMessage());
            try {
                String contentType = message.getContentType();
                String type = ObjectHelper.before(contentType, "charset=");
                if (type != null) {
                    // try again with fixed content type
                    LOG.debug("Trying to extract mail message again with fixed Content-Type: " + type);
                    // Since message is read-only, we need to use a copy
                    MimeMessage messageCopy = new MimeMessage((MimeMessage) message);
                    messageCopy.setHeader("Content-Type", type);
                    Object body = messageCopy.getContent();
                    // If we got this far, our fix worked...
                    // Replace the MailMessage's Message with the copy
                    mailMessage.setMessage(messageCopy);
                    return body;
                }
            } catch (Exception e2) {
                // fall through and let original exception be thrown
            }
        }

        throw new RuntimeCamelException("Failed to extract body due to: " + e.getMessage() + ". Exchange: "
                + exchange + ". Message: " + message, e);
    }
}

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

protected MessageDetails mimeToDetails(MimeMessage message, String folderName, long uid)
        throws IOException, MessagingException, UnsupportedEncodingException {
    MessageDetails mDetails = new MessageDetails();

    Object con = message.getContent();

    StringBuffer sbPlain = new StringBuffer();
    ArrayList<MessageAttachment> attachmentList = new ArrayList<MessageAttachment>();

    boolean isHTML = handleParts(message, con, sbPlain, attachmentList);

    System.out.println(isHTML);/* ww  w  .jav  a 2s . c o  m*/

    if (isHTML) {
        mDetails.setText(filterHtmlDocument(sbPlain.toString(), folderName, uid));
    } else {
        mDetails.setText(txtDocumentToHtml(sbPlain.toString(), folderName, uid));
    }

    mDetails.setMessageAttachments(attachmentList);

    mDetails.setRawHeader(message.getAllHeaders().toString());

    return mDetails;
}

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

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

    } else if (con instanceof Multipart) {

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

        String text = null;

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

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

                Boolean bodyRead = sbPlain.length() > 0;

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

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

    }
    return isHTML;
}

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

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

    } else if (content instanceof Multipart) {

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

        String text = null;

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

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

                Boolean bodyRead = sbPlain.length() > 0;

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

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

    }
    return isHTML;
}