001    /**
002     * Licensed to the Apache Software Foundation (ASF) under one or more
003     * contributor license agreements.  See the NOTICE file distributed with
004     * this work for additional information regarding copyright ownership.
005     * The ASF licenses this file to You under the Apache License, Version 2.0
006     * (the "License"); you may not use this file except in compliance with
007     * the License.  You may obtain a copy of the License at
008     *
009     *      http://www.apache.org/licenses/LICENSE-2.0
010     *
011     * Unless required by applicable law or agreed to in writing, software
012     * distributed under the License is distributed on an "AS IS" BASIS,
013     * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
014     * See the License for the specific language governing permissions and
015     * limitations under the License.
016     */
017    package org.apache.camel.component.mail;
018    
019    import java.io.IOException;
020    
021    import javax.mail.BodyPart;
022    import javax.mail.Message;
023    import javax.mail.MessagingException;
024    import javax.mail.Multipart;
025    import javax.mail.internet.MimeMultipart;
026    
027    import org.apache.camel.Converter;
028    
029    /**
030     * @version $Revision: 1.1 $
031     */
032    @Converter
033    public class MailConverters {
034        /**
035         * Converts the given JavaMail message to a String body
036         *
037         * @param message the message
038         * @return the String content
039         * @throws MessagingException
040         * @throws IOException
041         */
042        @Converter
043        public String toString(Message message) throws MessagingException, IOException {
044            Object content = message.getContent();
045            if (content instanceof MimeMultipart) {
046                MimeMultipart multipart = (MimeMultipart) content;
047                if (multipart.getCount() > 0) {
048                    BodyPart part = multipart.getBodyPart(0);
049                    content = part.getContent();
050                }
051            }
052            if (content != null) {
053                return content.toString();
054            }
055            return null;
056        }
057    
058        @Converter
059        public static String toString(Multipart multipart) throws MessagingException, IOException {
060            int size = multipart.getCount();
061            for (int i = 0; i < size; i++) {
062                BodyPart part = multipart.getBodyPart(i);
063                if (part.getContentType().startsWith("text")) {
064                    return part.getContent().toString();
065                }
066            }
067            return null;
068        }
069    }