Example usage for javax.mail.internet MimePart getContent

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

Introduction

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

Prototype

public Object getContent() throws IOException, MessagingException;

Source Link

Document

Return the content as a Java object.

Usage

From source file:com.zimbra.cs.mime.Mime.java

/** Returns the MimeMessage object encapsulating a MIME part with
 *  content-type "message/rfc822".  Use this method instead of
 *  {@link Part#getContent()} to work around JavaMail's fascism about
 *  proper MIME format and failure to support RFC 2184. */
public static MimeMessage getMessageContent(MimePart message822Part) throws IOException, MessagingException {
    String ctype = getContentType(message822Part);
    if (MimeConstants.CT_MESSAGE_RFC822.equals(ctype)) {
        // JavaMail will only return a correct MimeMessage if the Content-Type header was set correctly
        Object content = message822Part.getContent();
        if (content instanceof MimeMessage)
            return (MimeMessage) content;
    }//from w ww  .j a  v a2  s  . c  o m

    InputStream is = null;
    try {
        // handle unparsed content due to multipart/digest or miscapitalization of content-type value
        return new FixedMimeMessage(JMSession.getSession(), is = message822Part.getInputStream());
    } catch (Exception e) {
    } finally {
        ByteUtil.closeStream(is);
    }
    return null;
}

From source file:davmail.imap.ImapConnection.java

private void handleFetch(ExchangeSession.Message message, int currentIndex, String parameters)
        throws IOException, MessagingException {
    StringBuilder buffer = new StringBuilder();
    buffer.append("* ").append(currentIndex).append(" FETCH (UID ").append(message.getImapUid());
    if (parameters != null) {
        StringTokenizer paramTokens = new StringTokenizer(parameters);
        while (paramTokens.hasMoreTokens()) {
            @SuppressWarnings({ "NonConstantStringShouldBeStringBuffer" })
            String param = paramTokens.nextToken().toUpperCase();
            if ("FLAGS".equals(param)) {
                buffer.append(" FLAGS (").append(message.getImapFlags()).append(')');
            } else if ("RFC822.SIZE".equals(param)) {
                int size;
                if (parameters.indexOf("BODY.PEEK[HEADER.FIELDS (") >= 0) {
                    // Header request, send approximate size
                    size = message.size;
                } else {
                    size = message.getMimeMessageSize();
                }//from   w  ww. j  a v a 2 s  . co m
                buffer.append(" RFC822.SIZE ").append(size);
            } else if ("ENVELOPE".equals(param)) {
                appendEnvelope(buffer, message);
            } else if ("BODYSTRUCTURE".equals(param)) {
                appendBodyStructure(buffer, message);
            } else if ("INTERNALDATE".equals(param) && message.date != null && message.date.length() > 0) {
                try {
                    SimpleDateFormat dateParser = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSS'Z'");
                    dateParser.setTimeZone(ExchangeSession.GMT_TIMEZONE);
                    Date date = ExchangeSession.getZuluDateFormat().parse(message.date);
                    SimpleDateFormat dateFormatter = new SimpleDateFormat("dd-MMM-yyyy HH:mm:ss Z",
                            Locale.ENGLISH);
                    buffer.append(" INTERNALDATE \"").append(dateFormatter.format(date)).append('\"');
                } catch (ParseException e) {
                    throw new DavMailException("EXCEPTION_INVALID_DATE", message.date);
                }
            } else if (param.equals("RFC822") || param.startsWith("BODY[") || param.startsWith("BODY.PEEK[")
                    || "RFC822.HEADER".equals(param)) {
                // get full param
                if (param.indexOf('[') >= 0) {
                    StringBuilder paramBuffer = new StringBuilder(param);
                    while (paramTokens.hasMoreTokens() && paramBuffer.indexOf("]") < 0) {
                        paramBuffer.append(' ').append(paramTokens.nextToken());
                    }
                    param = paramBuffer.toString();
                }
                // parse buffer size
                int startIndex = 0;
                int maxSize = Integer.MAX_VALUE;
                int ltIndex = param.indexOf('<');
                if (ltIndex >= 0) {
                    int dotIndex = param.indexOf('.', ltIndex);
                    if (dotIndex >= 0) {
                        startIndex = Integer.parseInt(param.substring(ltIndex + 1, dotIndex));
                        maxSize = Integer.parseInt(param.substring(dotIndex + 1, param.indexOf('>')));
                    }
                }

                ByteArrayOutputStream baos = new ByteArrayOutputStream();
                InputStream partInputStream = null;
                OutputStream partOutputStream = null;

                // try to parse message part index
                String partIndexString = StringUtil.getToken(param, "[", "]");
                if ("".equals(partIndexString) || partIndexString == null) {
                    // write message with headers
                    partOutputStream = new PartialOutputStream(baos, startIndex, maxSize);
                    partInputStream = message.getRawInputStream();
                } else if ("TEXT".equals(partIndexString)) {
                    // write message without headers
                    partOutputStream = new PartialOutputStream(baos, startIndex, maxSize);
                    partInputStream = message.getMimeMessage().getRawInputStream();
                } else if ("RFC822.HEADER".equals(param) || partIndexString.startsWith("HEADER")) {
                    // Header requested fetch  headers
                    String[] requestedHeaders = getRequestedHeaders(partIndexString);
                    if (requestedHeaders != null) {
                        // OSX Lion special flags request
                        if (requestedHeaders.length == 1 && "content-class".equals(requestedHeaders[0])
                                && message.contentClass != null) {
                            baos.write("Content-class: ".getBytes("UTF-8"));
                            baos.write(message.contentClass.getBytes("UTF-8"));
                            baos.write(13);
                            baos.write(10);
                        } else {
                            Enumeration headerEnumeration = message.getMatchingHeaderLines(requestedHeaders);
                            while (headerEnumeration.hasMoreElements()) {
                                baos.write(((String) headerEnumeration.nextElement()).getBytes("UTF-8"));
                                baos.write(13);
                                baos.write(10);
                            }
                        }
                    } else {
                        // write headers only
                        partOutputStream = new PartOutputStream(baos, true, false, startIndex, maxSize);
                        partInputStream = message.getRawInputStream();
                    }
                } else {
                    MimePart bodyPart = message.getMimeMessage();
                    String[] partIndexStrings = partIndexString.split("\\.");
                    for (String subPartIndexString : partIndexStrings) {
                        // ignore MIME subpart index, will return full part
                        if ("MIME".equals(subPartIndexString)) {
                            break;
                        }
                        int subPartIndex;
                        // try to parse part index
                        try {
                            subPartIndex = Integer.parseInt(subPartIndexString);
                        } catch (NumberFormatException e) {
                            throw new DavMailException("EXCEPTION_INVALID_PARAMETER", param);
                        }

                        Object mimeBody = bodyPart.getContent();
                        if (mimeBody instanceof MimeMultipart) {
                            MimeMultipart multiPart = (MimeMultipart) mimeBody;
                            if (subPartIndex - 1 < multiPart.getCount()) {
                                bodyPart = (MimePart) multiPart.getBodyPart(subPartIndex - 1);
                            } else {
                                throw new DavMailException("EXCEPTION_INVALID_PARAMETER", param);
                            }
                        } else if (subPartIndex != 1) {
                            throw new DavMailException("EXCEPTION_INVALID_PARAMETER", param);
                        }
                    }

                    // write selected part, without headers
                    partOutputStream = new PartialOutputStream(baos, startIndex, maxSize);
                    if (bodyPart instanceof MimeMessage) {
                        partInputStream = ((MimeMessage) bodyPart).getRawInputStream();
                    } else {
                        partInputStream = ((MimeBodyPart) bodyPart).getRawInputStream();
                    }
                }

                // copy selected content to baos
                if (partInputStream != null && partOutputStream != null) {
                    IOUtil.write(partInputStream, partOutputStream);
                    partInputStream.close();
                    partOutputStream.close();
                }
                baos.close();

                if ("RFC822.HEADER".equals(param)) {
                    buffer.append(" RFC822.HEADER ");
                } else {
                    buffer.append(" BODY[").append(partIndexString).append(']');
                }
                // partial
                if (startIndex > 0 || maxSize != Integer.MAX_VALUE) {
                    buffer.append('<').append(startIndex).append('>');
                }
                buffer.append(" {").append(baos.size()).append('}');
                sendClient(buffer.toString());
                // log content if less than 2K
                if (LOGGER.isDebugEnabled() && baos.size() < 2048) {
                    LOGGER.debug(new String(baos.toByteArray(), "UTF-8"));
                }
                os.write(baos.toByteArray());
                os.flush();
                buffer.setLength(0);
            }
        }
    }
    buffer.append(')');
    sendClient(buffer.toString());
    // do not keep message content in memory
    message.dropMimeMessage();
}

From source file:davmail.exchange.dav.DavExchangeSession.java

/**
 * Create message in specified folder.//from  w  w w. j  a va2  s .  c o m
 * Will overwrite an existing message with same messageName in the same folder
 *
 * @param folderPath  Exchange folder path
 * @param messageName message name
 * @param properties  message properties (flags)
 * @param mimeMessage MIME message
 * @throws IOException when unable to create message
 */
@Override
public void createMessage(String folderPath, String messageName, HashMap<String, String> properties,
        MimeMessage mimeMessage) throws IOException {
    String messageUrl = URIUtil.encodePathQuery(getFolderPath(folderPath) + '/' + messageName);
    PropPatchMethod patchMethod;
    List<PropEntry> davProperties = buildProperties(properties);

    if (properties != null && properties.containsKey("draft")) {
        // note: draft is readonly after create, create the message first with requested messageFlags
        davProperties.add(Field.createDavProperty("messageFlags", properties.get("draft")));
    }
    if (properties != null && properties.containsKey("mailOverrideFormat")) {
        davProperties.add(Field.createDavProperty("mailOverrideFormat", properties.get("mailOverrideFormat")));
    }
    if (properties != null && properties.containsKey("messageFormat")) {
        davProperties.add(Field.createDavProperty("messageFormat", properties.get("messageFormat")));
    }
    if (!davProperties.isEmpty()) {
        patchMethod = new PropPatchMethod(messageUrl, davProperties);
        try {
            // update message with blind carbon copy and other flags
            int statusCode = httpClient.executeMethod(patchMethod);
            if (statusCode != HttpStatus.SC_MULTI_STATUS) {
                throw new DavMailException("EXCEPTION_UNABLE_TO_CREATE_MESSAGE", messageUrl, statusCode, ' ',
                        patchMethod.getStatusLine());
            }

        } finally {
            patchMethod.releaseConnection();
        }
    }

    // update message body
    PutMethod putmethod = new PutMethod(messageUrl);
    putmethod.setRequestHeader("Translate", "f");
    putmethod.setRequestHeader("Content-Type", "message/rfc822");

    try {
        // use same encoding as client socket reader
        ByteArrayOutputStream baos = new ByteArrayOutputStream();
        mimeMessage.writeTo(baos);
        baos.close();
        putmethod.setRequestEntity(new ByteArrayRequestEntity(baos.toByteArray()));
        int code = httpClient.executeMethod(putmethod);

        // workaround for misconfigured Exchange server
        if (code == HttpStatus.SC_NOT_ACCEPTABLE) {
            LOGGER.warn(
                    "Draft message creation failed, failover to property update. Note: attachments are lost");

            ArrayList<PropEntry> propertyList = new ArrayList<PropEntry>();
            propertyList.add(Field.createDavProperty("to", mimeMessage.getHeader("to", ",")));
            propertyList.add(Field.createDavProperty("cc", mimeMessage.getHeader("cc", ",")));
            propertyList.add(Field.createDavProperty("message-id", mimeMessage.getHeader("message-id", ",")));

            MimePart mimePart = mimeMessage;
            if (mimeMessage.getContent() instanceof MimeMultipart) {
                MimeMultipart multiPart = (MimeMultipart) mimeMessage.getContent();
                for (int i = 0; i < multiPart.getCount(); i++) {
                    String contentType = multiPart.getBodyPart(i).getContentType();
                    if (contentType.startsWith("text/")) {
                        mimePart = (MimePart) multiPart.getBodyPart(i);
                        break;
                    }
                }
            }

            String contentType = mimePart.getContentType();

            if (contentType.startsWith("text/plain")) {
                propertyList.add(Field.createDavProperty("description", (String) mimePart.getContent()));
            } else if (contentType.startsWith("text/html")) {
                propertyList.add(Field.createDavProperty("htmldescription", (String) mimePart.getContent()));
            } else {
                LOGGER.warn("Unsupported content type: " + contentType + " message body will be empty");
            }

            propertyList.add(Field.createDavProperty("subject", mimeMessage.getHeader("subject", ",")));
            PropPatchMethod propPatchMethod = new PropPatchMethod(messageUrl, propertyList);
            try {
                int patchStatus = DavGatewayHttpClientFacade.executeHttpMethod(httpClient, propPatchMethod);
                if (patchStatus == HttpStatus.SC_MULTI_STATUS) {
                    code = HttpStatus.SC_OK;
                }
            } finally {
                propPatchMethod.releaseConnection();
            }
        }

        if (code != HttpStatus.SC_OK && code != HttpStatus.SC_CREATED) {

            // first delete draft message
            if (!davProperties.isEmpty()) {
                try {
                    DavGatewayHttpClientFacade.executeDeleteMethod(httpClient, messageUrl);
                } catch (IOException e) {
                    LOGGER.warn("Unable to delete draft message");
                }
            }
            if (code == HttpStatus.SC_INSUFFICIENT_STORAGE) {
                throw new InsufficientStorageException(putmethod.getStatusText());
            } else {
                throw new DavMailException("EXCEPTION_UNABLE_TO_CREATE_MESSAGE", messageUrl, code, ' ',
                        putmethod.getStatusLine());
            }
        }
    } catch (MessagingException e) {
        throw new IOException(e.getMessage());
    } finally {
        putmethod.releaseConnection();
    }

    try {
        // need to update bcc after put
        if (mimeMessage.getHeader("Bcc") != null) {
            davProperties = new ArrayList<PropEntry>();
            davProperties.add(Field.createDavProperty("bcc", mimeMessage.getHeader("Bcc", ",")));
            patchMethod = new PropPatchMethod(messageUrl, davProperties);
            try {
                // update message with blind carbon copy
                int statusCode = httpClient.executeMethod(patchMethod);
                if (statusCode != HttpStatus.SC_MULTI_STATUS) {
                    throw new DavMailException("EXCEPTION_UNABLE_TO_CREATE_MESSAGE", messageUrl, statusCode,
                            ' ', patchMethod.getStatusLine());
                }

            } finally {
                patchMethod.releaseConnection();
            }
        }
    } catch (MessagingException e) {
        throw new IOException(e.getMessage());
    }

}

From source file:com.icegreen.greenmail.store.SimpleMessageAttributes.java

/**
 * Parses key data items from a MimeMessage for seperate storage.
 * TODO this is a mess, and should be completely revamped.
 *//*w  ww.j a  v  a 2  s .c  o  m*/
void parseMimePart(MimePart part) throws MessagingException {
    size = GreenMailUtil.getBody(part).length();

    // Section 1 - Message Headers
    if (part instanceof MimeMessage) {
        try {
            subject = ((MimeMessage) part).getSubject();
        } catch (MessagingException me) {
            //                if (DEBUG) getLogger().debug("Messaging Exception for getSubject: " + me);
        }
    }
    try {
        from = part.getHeader("From");
    } catch (MessagingException me) {
        //            if (DEBUG) getLogger().debug("Messaging Exception for getHeader(From): " + me);
    }
    try {
        sender = part.getHeader("Sender");
    } catch (MessagingException me) {
        //            if (DEBUG) getLogger().debug("Messaging Exception for getHeader(Sender): " + me);
    }
    try {
        replyTo = part.getHeader("Reply To");
    } catch (MessagingException me) {
        //            if (DEBUG) getLogger().debug("Messaging Exception for getHeader(Reply To): " + me);
    }
    try {
        to = part.getHeader("To");
    } catch (MessagingException me) {
        //            if (DEBUG) getLogger().debug("Messaging Exception for getHeader(To): " + me);
    }
    try {
        cc = part.getHeader("Cc");
    } catch (MessagingException me) {
        //            if (DEBUG) getLogger().debug("Messaging Exception for getHeader(To): " + me);
    }
    try {
        bcc = part.getHeader("Bcc");
    } catch (MessagingException me) {
        //            if (DEBUG) getLogger().debug("Messaging Exception for getHeader(To): " + me);
    }
    try {
        inReplyTo = part.getHeader("In Reply To");
    } catch (MessagingException me) {
        //            if (DEBUG) getLogger().debug("Messaging Exception for getHeader(In Reply To): " + me);
    }
    try {
        date = part.getHeader("Date");
    } catch (MessagingException me) {
        //            if (DEBUG) getLogger().debug("Messaging Exception for getHeader(Date): " + me);
    }
    try {
        messageID = part.getHeader("Message-ID");
    } catch (MessagingException me) {
        //            if (DEBUG) getLogger().debug("Messaging Exception for getHeader(messageID): " + me);
    }
    String contentTypeLine = null;
    try {
        contentTypeLine = part.getContentType();
    } catch (MessagingException me) {
        //            if (DEBUG) getLogger().debug("Messaging Exception for getContentType(): " + me);
    }
    if (contentTypeLine != null) {
        decodeContentType(contentTypeLine);
    }
    try {
        contentID = part.getContentID();
    } catch (MessagingException me) {
        //            if (DEBUG) getLogger().debug("Messaging Exception for getContentUD(): " + me);
    }
    try {
        contentDesc = part.getDescription();
    } catch (MessagingException me) {
        //            if (DEBUG) getLogger().debug("Messaging Exception for getDescription(): " + me);
    }
    try {
        contentEncoding = part.getEncoding();
        // default value.
        if (contentEncoding == null) {
            contentEncoding = "7BIT";
        }
    } catch (MessagingException me) {
        //            if (DEBUG) getLogger().debug("Messaging Exception for getEncoding(): " + me);
    }

    try {
        //            contentDisposition = part.getDisposition();
        contentDisposition = Header.create(part.getHeader("Content-Disposition"));
    } catch (MessagingException me) {
        if (log.isDebugEnabled()) {
            log.debug("Can not create content disposition for part " + part, me);
        }
    }

    try {
        // TODO this doesn't work
        lineCount = getLineCount(part);
    } catch (Exception e) {
        if (log.isDebugEnabled()) {
            log.debug("Can not get line count for part " + part, e);
        }
    }

    // Recurse through any embedded parts
    if (primaryType.equalsIgnoreCase(MULTIPART)) {
        MimeMultipart container;
        try {
            container = (MimeMultipart) part.getContent();
            int count = container.getCount();
            parts = new SimpleMessageAttributes[count];
            for (int i = 0; i < count; i++) {
                BodyPart nextPart = container.getBodyPart(i);

                if (nextPart instanceof MimePart) {
                    SimpleMessageAttributes partAttrs = new SimpleMessageAttributes(null, receivedDate);
                    partAttrs.parseMimePart((MimePart) nextPart);
                    parts[i] = partAttrs;

                }
            }
        } catch (Exception e) {
            if (log.isDebugEnabled()) {
                log.debug("Can not recurse through multipart content", e);
            }
        }
    } else if (primaryType.equalsIgnoreCase("message")) {
        if (secondaryType.equalsIgnoreCase("RFC822")) {
            //try {

            /*
            MimeMessageWrapper message = new MimeMessageWrapper(part.getInputStream());
            SimpleMessageAttributes msgAttrs = new SimpleMessageAttributes();
            msgAttrs.setAttributesFor(message);
                    
            if (part instanceof MimeMessage) {
            Comments out because I don't know what it should do here
            MimeMessage msg1 = (MimeMessage) part;
            MimeMessageWrapper message2 = new MimeMessageWrapper(msg1);
            SimpleMessageAttributes msgAttrs2 = new SimpleMessageAttributes();
            msgAttrs.setAttributesFor(message2);
            }
                    
            parts = new SimpleMessageAttributes[1];
            parts[0] = msgAttrs;
            */
            //} catch (Exception e) {
            //getLogger().error("Error interpreting a message/rfc822: " + e);
            //e.printStackTrace();
            //}

            // TODO: Warn till fixed!
            log.warn("Unknown/unhandled subtype " + secondaryType + " of message encountered.");
        } else {
            log.warn("Unknown/unhandled subtype " + secondaryType + " of message encountered.");
        }
    }
}

From source file:org.apache.james.smtpserver.fastfail.URIRBLHandler.java

/**
 * Recursively scans all MimeParts of an email for domain strings. Domain
 * strings that are found are added to the supplied HashSet.
 * //ww  w  . j  a  v a  2 s  . com
 * @param part
 *            MimePart to scan
 * @param session
 *            not null
 * @return domains The HashSet that contains the domains which were
 *         extracted
 */
private HashSet<String> scanMailForDomains(MimePart part, SMTPSession session)
        throws MessagingException, IOException {
    HashSet<String> domains = new HashSet<String>();
    session.getLogger().debug("mime type is: \"" + part.getContentType() + "\"");

    if (part.isMimeType("text/plain") || part.isMimeType("text/html")) {
        session.getLogger().debug("scanning: \"" + part.getContent().toString() + "\"");
        HashSet<String> newDom = URIScanner.scanContentForDomains(domains, part.getContent().toString());

        // Check if new domains are found and add the domains
        if (newDom != null && newDom.size() > 0) {
            domains.addAll(newDom);
        }
    } else if (part.isMimeType("multipart/*")) {
        MimeMultipart multipart = (MimeMultipart) part.getContent();
        int count = multipart.getCount();
        session.getLogger().debug("multipart count is: " + count);

        for (int index = 0; index < count; index++) {
            session.getLogger().debug("recursing index: " + index);
            MimeBodyPart mimeBodyPart = (MimeBodyPart) multipart.getBodyPart(index);
            HashSet<String> newDomains = scanMailForDomains(mimeBodyPart, session);

            // Check if new domains are found and add the domains
            if (newDomains != null && newDomains.size() > 0) {
                domains.addAll(newDomains);
            }
        }
    }
    return domains;
}

From source file:org.simplejavamail.internal.util.MimeMessageParser.java

/**
 * Extracts the content of a MimeMessage recursively.
 *
 * @param part   the current MimePart/* w  w  w .ja va 2s  .  co  m*/
 * @throws MessagingException parsing the MimeMessage failed
 * @throws IOException        parsing the MimeMessage failed
 */
private void parse(final MimePart part) throws MessagingException, IOException {
    extractCustomUserHeaders(part);

    if (isMimeType(part, "text/plain") && plainContent == null
            && !Part.ATTACHMENT.equalsIgnoreCase(part.getDisposition())) {
        plainContent = (String) part.getContent();
    } else {
        if (isMimeType(part, "text/html") && htmlContent == null
                && !Part.ATTACHMENT.equalsIgnoreCase(part.getDisposition())) {
            htmlContent = (String) part.getContent();
        } else {
            if (isMimeType(part, "multipart/*")) {
                final Multipart mp = (Multipart) part.getContent();
                final int count = mp.getCount();

                // iterate over all MimeBodyPart
                for (int i = 0; i < count; i++) {
                    parse((MimeBodyPart) mp.getBodyPart(i));
                }
            } else {
                final DataSource ds = createDataSource(part);
                // If the diposition is not provided, the part should be treat as attachment
                if (part.getDisposition() == null || Part.ATTACHMENT.equalsIgnoreCase(part.getDisposition())) {
                    this.attachmentList.put(part.getContentID(), ds);
                } else if (Part.INLINE.equalsIgnoreCase(part.getDisposition())) {
                    this.cidMap.put(part.getContentID(), ds);
                } else {
                    throw new IllegalStateException("invalid attachment type");
                }
            }
        }
    }
}