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.net.URI;
020    import java.util.HashMap;
021    import java.util.Map;
022    import java.util.Properties;
023    import javax.mail.Authenticator;
024    import javax.mail.Message;
025    import javax.mail.PasswordAuthentication;
026    import javax.mail.Session;
027    
028    import org.apache.camel.RuntimeCamelException;
029    import org.springframework.mail.javamail.JavaMailSenderImpl;
030    
031    /**
032     * Represents the configuration data for communicating over email
033     *
034     * @version $Revision: 787632 $
035     */
036    public class MailConfiguration implements Cloneable {
037    
038        public static final String DEFAULT_FOLDER_NAME = "INBOX";
039        public static final String DEFAULT_FROM = "camel@localhost";
040        public static final String DEFAULT_ALTERNATE_BODY_HEADER = "mail_alternateBody";
041        public static final long DEFAULT_CONNECTION_TIMEOUT = 30000L;
042    
043        private Properties javaMailProperties;
044        private String protocol;
045        private String host;
046        private int port = -1;
047        private String username;
048        private String password;
049        private Session session;
050        private String defaultEncoding;
051        private String from = DEFAULT_FROM;
052        private String folderName = DEFAULT_FOLDER_NAME;
053        private boolean deleteProcessedMessages;
054        private boolean ignoreUriScheme;
055        private boolean processOnlyUnseenMessages = true;
056        private Map<Message.RecipientType, String> recipients = new HashMap<Message.RecipientType, String>();
057        private String destination;
058        private int fetchSize = -1;
059        private boolean debugMode;
060        private long connectionTimeout = DEFAULT_CONNECTION_TIMEOUT;
061        private boolean dummyTrustManager;
062        private String contentType = "text/plain";
063        private String alternateBodyHeader = DEFAULT_ALTERNATE_BODY_HEADER;
064        private boolean useInlineAttachments;
065    
066        public MailConfiguration() {
067        }
068    
069        /**
070         * Returns a copy of this configuration
071         */
072        public MailConfiguration copy() {
073            try {
074                return (MailConfiguration) clone();
075            } catch (CloneNotSupportedException e) {
076                throw new RuntimeCamelException(e);
077            }
078        }
079    
080        public void configure(URI uri) {
081            String value = uri.getHost();
082            if (value != null) {
083                setHost(value);
084            }
085    
086            if (!isIgnoreUriScheme()) {
087                String scheme = uri.getScheme();
088                if (scheme != null) {
089                    setProtocol(scheme);
090                }
091            }
092    
093            String userInfo = uri.getUserInfo();
094            if (userInfo != null) {
095                setUsername(userInfo);
096            }
097    
098            int port = uri.getPort();
099            if (port > 0) {
100                setPort(port);
101            } else if (port <= 0 && this.port <= 0) {
102                // resolve default port if no port number was provided, and not already configured with a port number
103                setPort(MailUtils.getDefaultPortForProtocol(uri.getScheme()));
104            }
105        }
106    
107        protected JavaMailSenderImpl createJavaMailSender() {
108            JavaMailSenderImpl answer = new JavaMailSenderImpl();
109    
110            // sets the debug mode of the underlying mail framework
111            answer.getSession().setDebug(debugMode);
112    
113            // java mail properties
114            Properties prop = javaMailProperties;
115            if (prop == null) {
116                // set default properties if none provided
117                prop = createJavaMailProperties();
118            }
119            answer.setJavaMailProperties(prop);
120    
121            if (defaultEncoding != null) {
122                answer.setDefaultEncoding(defaultEncoding);
123            }
124            if (host != null) {
125                answer.setHost(host);
126            }
127            if (port >= 0) {
128                answer.setPort(port);
129            }
130            if (password != null) {
131                answer.setPassword(password);
132            }
133            if (protocol != null) {
134                answer.setProtocol(protocol);
135            }
136            if (session != null) {
137                answer.setSession(session);
138            } else {
139                // use our authenticator that does no live user interaction but returns the already configured username and password
140                Session session = Session.getDefaultInstance(prop, getAuthenticator());
141                answer.setSession(session);
142            }
143            if (username != null) {
144                answer.setUsername(username);
145            }
146    
147            return answer;
148        }
149    
150        private Properties createJavaMailProperties() {
151            // clone the system properties and set the java mail properties
152            Properties properties = (Properties)System.getProperties().clone();
153            properties.put("mail." + protocol + ".connectiontimeout", connectionTimeout);
154            properties.put("mail." + protocol + ".timeout", connectionTimeout);
155            properties.put("mail." + protocol + ".host", host);
156            properties.put("mail." + protocol + ".port", "" + port);
157            if (username != null) {
158                properties.put("mail." + protocol + ".user", username);
159                properties.put("mail.user", username);
160                properties.put("mail." + protocol + ".auth", "true");
161            } else {
162                properties.put("mail." + protocol + ".auth", "false");
163            }
164            properties.put("mail." + protocol + ".rsetbeforequit", "true");
165            properties.put("mail.transport.protocol", protocol);
166            properties.put("mail.store.protocol", protocol);
167            properties.put("mail.host", host);
168    
169            if (debugMode) {
170                // add more debug for the SSL communication as well
171                properties.put("javax.net.debug", "all");
172            }
173    
174            if (dummyTrustManager && isSecureProtocol()) {
175                // set the custom SSL properties
176                properties.put("mail." + protocol + ".socketFactory.class", "org.apache.camel.component.mail.security.DummySSLSocketFactory");
177                properties.put("mail." + protocol + ".socketFactory.fallback", "false");
178                properties.put("mail." + protocol + ".socketFactory.port", "" + port);
179            }
180    
181            return properties;
182        }
183    
184        /**
185         * Is the used protocol to be secure or not
186         */
187        public boolean isSecureProtocol() {
188            return this.protocol.equalsIgnoreCase("smtps") || this.protocol.equalsIgnoreCase("pop3s")
189                   || this.protocol.equalsIgnoreCase("imaps");
190        }
191    
192        /**
193         * Returns an authenticator object for use in sessions
194         */
195        public Authenticator getAuthenticator() {
196            return new Authenticator() {
197                protected PasswordAuthentication getPasswordAuthentication() {
198                    return new PasswordAuthentication(getUsername(), getPassword());
199                }
200            };
201        }
202    
203        public String getMailStoreLogInformation() {
204            String ssl = "";
205            if (isSecureProtocol()) {
206                ssl = "(SSL enabled" + (dummyTrustManager ? " using DummyTrustManager)" : ")");
207            }
208    
209            return protocol + "//" + host + ":" + port + ssl + ", folder=" + folderName;
210        }
211    
212        // Properties
213        // -------------------------------------------------------------------------
214    
215        public String getDefaultEncoding() {
216            return defaultEncoding;
217        }
218    
219        public void setDefaultEncoding(String defaultEncoding) {
220            this.defaultEncoding = defaultEncoding;
221        }
222    
223        public String getHost() {
224            return host;
225        }
226    
227        public void setHost(String host) {
228            this.host = host;
229        }
230    
231        public Properties getJavaMailProperties() {
232            return javaMailProperties;
233        }
234    
235        public void setJavaMailProperties(Properties javaMailProperties) {
236            this.javaMailProperties = javaMailProperties;
237        }
238    
239        public String getPassword() {
240            return password;
241        }
242    
243        public void setPassword(String password) {
244            this.password = password;
245        }
246    
247        public int getPort() {
248            return port;
249        }
250    
251        public void setPort(int port) {
252            this.port = port;
253        }
254    
255        public String getProtocol() {
256            return protocol;
257        }
258    
259        public void setProtocol(String protocol) {
260            this.protocol = protocol;
261        }
262    
263        public Session getSession() {
264            return session;
265        }
266    
267        public void setSession(Session session) {
268            this.session = session;
269        }
270    
271        public String getUsername() {
272            return username;
273        }
274    
275        public void setUsername(String username) {
276            this.username = username;
277            if (destination == null) {
278                // set default destination to username@host for backwards compatibility
279                // can be overridden by URI parameters
280                String address = username;
281                if (address.indexOf("@") == -1) {
282                    address += "@" + host;
283                }
284                destination = address;
285            }
286        }
287    
288        /**
289         * Gets the destination (recipient <tt>To</tt> email address).
290         *
291         * @deprecated use {@link #getRecipients()}
292         */
293        public String getDestination() {
294            return destination;
295        }
296    
297        /**
298         * Sets the destination (recipient <tt>To</tt> email address).
299         *
300         * @deprecated use {@link #setTo(String)}
301         */
302        public void setDestination(String destination) {
303            this.destination = destination;
304        }
305    
306        public String getFrom() {
307            return from;
308        }
309    
310        public void setFrom(String from) {
311            this.from = from;
312        }
313    
314        public boolean isDeleteProcessedMessages() {
315            return deleteProcessedMessages;
316        }
317    
318        public void setDeleteProcessedMessages(boolean deleteProcessedMessages) {
319            this.deleteProcessedMessages = deleteProcessedMessages;
320        }
321    
322        public String getFolderName() {
323            return folderName;
324        }
325    
326        public void setFolderName(String folderName) {
327            this.folderName = folderName;
328        }
329    
330        public boolean isIgnoreUriScheme() {
331            return ignoreUriScheme;
332        }
333    
334        public void setIgnoreUriScheme(boolean ignoreUriScheme) {
335            this.ignoreUriScheme = ignoreUriScheme;
336        }
337    
338        public boolean isProcessOnlyUnseenMessages() {
339            return processOnlyUnseenMessages;
340        }
341    
342        public void setProcessOnlyUnseenMessages(boolean processOnlyUnseenMessages) {
343            this.processOnlyUnseenMessages = processOnlyUnseenMessages;
344        }
345    
346        /**
347         * Sets the <tt>To</tt> email address. Separate multiple email addresses with comma.
348         */
349        public void setTo(String address) {
350            recipients.put(Message.RecipientType.TO, address);
351        }
352    
353        /**
354         * Sets the <tt>CC</tt> email address. Separate multiple email addresses with comma.
355         */
356        public void setCC(String address) {
357            recipients.put(Message.RecipientType.CC, address);
358        }
359    
360        /**
361         * Sets the <tt>BCC</tt> email address. Separate multiple email addresses with comma.
362         */
363        public void setBCC(String address) {
364            recipients.put(Message.RecipientType.BCC, address);
365        }
366    
367        public Map<Message.RecipientType, String> getRecipients() {
368            return recipients;
369        }
370    
371        public int getFetchSize() {
372            return fetchSize;
373        }
374    
375        public void setFetchSize(int fetchSize) {
376            this.fetchSize = fetchSize;
377        }
378    
379        public boolean isDebugMode() {
380            return debugMode;
381        }
382    
383        public void setDebugMode(boolean debugMode) {
384            this.debugMode = debugMode;
385        }
386    
387        public long getConnectionTimeout() {
388            return connectionTimeout;
389        }
390    
391        public void setConnectionTimeout(long connectionTimeout) {
392            this.connectionTimeout = connectionTimeout;
393        }
394    
395        public boolean isDummyTrustManager() {
396            return dummyTrustManager;
397        }
398    
399        public void setDummyTrustManager(boolean dummyTrustManager) {
400            this.dummyTrustManager = dummyTrustManager;
401        }
402    
403        public String getContentType() {
404            return contentType;
405        }
406    
407        public void setContentType(String contentType) {
408            this.contentType = contentType;
409        }
410    
411        public String getAlternateBodyHeader() {
412            return alternateBodyHeader;
413        }
414    
415        public void setAlternateBodyHeader(String alternateBodyHeader) {
416            this.alternateBodyHeader = alternateBodyHeader;
417        }
418    
419        public boolean isUseInlineAttachments() {
420            return useInlineAttachments;
421        }
422    
423        public void setUseInlineAttachments(boolean useInlineAttachments) {
424            this.useInlineAttachments = useInlineAttachments;
425        }
426    }