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.util.Iterator;
020    import java.util.Map;
021    import java.util.Set;
022    
023    import javax.mail.Address;
024    import javax.mail.Message;
025    import javax.mail.MessagingException;
026    import javax.mail.internet.InternetAddress;
027    import javax.mail.internet.MimeMessage;
028    
029    import org.apache.camel.Exchange;
030    import org.apache.camel.converter.ObjectConverter;
031    
032    /**
033     * A Strategy used to convert between a Camel {@Exchange} and {@Message} to and
034     * from a Mail {@link MimeMessage}
035     * 
036     * @version $Revision: 521240 $
037     */
038    public class MailBinding {
039        public void populateMailMessage(MailEndpoint endpoint, MimeMessage mimeMessage, Exchange exchange) {
040            try {
041                appendHeadersFromCamel(mimeMessage, exchange, exchange.getIn());
042    
043                String destination = endpoint.getConfiguration().getDestination();
044                if (destination != null) {
045                    mimeMessage.setRecipients(Message.RecipientType.TO, destination);
046                }
047    
048                if (empty(mimeMessage.getFrom())) {
049                    // lets default the address to the endpoint destination
050                    String from = endpoint.getConfiguration().getFrom();
051                    mimeMessage.setFrom(new InternetAddress(from));
052                }
053                mimeMessage.setText(exchange.getIn().getBody(String.class));
054            } catch (Exception e) {
055                throw new RuntimeMailException("Failed to populate body due to: " + e + ". Exchange: " + exchange, e);
056            }
057        }
058    
059        protected boolean empty(Address[] addresses) {
060            return addresses == null || addresses.length == 0;
061        }
062    
063        /**
064         * Extracts the body from the Mail message
065         * 
066         * @param exchange
067         * @param message
068         */
069        public Object extractBodyFromMail(MailExchange exchange, Message message) {
070            try {
071                return message.getContent();
072            } catch (Exception e) {
073                throw new RuntimeMailException("Failed to extract body due to: " + e + ". Message: " + message, e);
074            }
075        }
076    
077        /**
078         * Appends the Mail headers from the Camel {@link MailMessage}
079         */
080        protected void appendHeadersFromCamel(MimeMessage mimeMessage, Exchange exchange, org.apache.camel.Message camelMessage) throws MessagingException {
081            Set<Map.Entry<String, Object>> entries = camelMessage.getHeaders().entrySet();
082            for (Map.Entry<String, Object> entry : entries) {
083                String headerName = entry.getKey();
084                Object headerValue = entry.getValue();
085                if (headerValue != null) {
086                    if (shouldOutputHeader(camelMessage, headerName, headerValue)) {
087    
088                        // Mail messages can repeat the same header...
089                        if (ObjectConverter.isCollection(headerValue)) {
090                            Iterator iter = ObjectConverter.iterator(headerValue);
091                            while (iter.hasNext()) {
092                                Object value = iter.next();
093                                mimeMessage.addHeader(headerName, asString(exchange, value));
094                            }
095                        } else {
096                            mimeMessage.setHeader(headerName, asString(exchange, headerValue));
097                        }
098                    }
099                }
100            }
101        }
102    
103        /**
104         * Converts the given object value to a String
105         */
106        protected String asString(Exchange exchange, Object value) {
107            return exchange.getContext().getTypeConverter().convertTo(String.class, value);
108        }
109    
110        /**
111         * Strategy to allow filtering of headers which are put on the Mail message
112         */
113        protected boolean shouldOutputHeader(org.apache.camel.Message camelMessage, String headerName, Object headerValue) {
114            return true;
115        }
116    }