KickJava   Java API By Example, From Geeks To Geeks.

Java > Open Source Codes > org > mule > providers > email > MailUtils


1 /*
2  * $Id: MailUtils.java 4219 2006-12-09 10:15:14Z lajos $
3  * --------------------------------------------------------------------------------------
4  * Copyright (c) MuleSource, Inc. All rights reserved. http://www.mulesource.com
5  *
6  * The software in this package is published under the terms of the MuleSource MPL
7  * license, a copy of which has been included with this distribution in the
8  * LICENSE.txt file.
9  */

10
11 package org.mule.providers.email;
12
13 import java.util.Properties JavaDoc;
14
15 import javax.mail.Address JavaDoc;
16 import javax.mail.Authenticator JavaDoc;
17 import javax.mail.PasswordAuthentication JavaDoc;
18 import javax.mail.Session JavaDoc;
19 import javax.mail.URLName JavaDoc;
20 import javax.mail.internet.AddressException JavaDoc;
21 import javax.mail.internet.InternetAddress JavaDoc;
22
23 import org.apache.commons.lang.StringUtils;
24 import org.apache.commons.logging.Log;
25 import org.apache.commons.logging.LogFactory;
26 import org.mule.config.i18n.Messages;
27
28 /**
29  * Contains javax.mail.Session helpers.
30  */

31 public class MailUtils
32 {
33     /**
34      * The logger used for this class
35      */

36     protected final static Log logger = LogFactory.getLog(MailUtils.class);
37
38     /**
39      * Creates a new Mail session based on a Url. this method will also add an Smtp
40      * Authenticator if a password is set on the URL
41      *
42      * @param url
43      * @return initialised mail session
44      */

45     public static Session JavaDoc createMailSession(URLName JavaDoc url, MailConnector connector)
46     {
47         if (url == null)
48         {
49             throw new IllegalArgumentException JavaDoc(
50                 new org.mule.config.i18n.Message(Messages.X_IS_NULL, "URL").toString());
51         }
52         String JavaDoc protocol = connector.getProtocol().toLowerCase();
53         boolean secure = false;
54         if (protocol.equals("smtps"))
55         {
56             protocol = "smtp";
57             secure = true;
58         }
59         else if (protocol.equals("pop3s"))
60         {
61             protocol = "pop3";
62             secure = true;
63         }
64         else if (protocol.equals("imaps"))
65         {
66             protocol = "imap";
67             secure = true;
68         }
69
70         Properties JavaDoc props = System.getProperties();
71         Session JavaDoc session;
72
73         // make sure we do not mess with authentication set via system properties
74
synchronized (props)
75         {
76             props.put("mail." + protocol + ".host", url.getHost());
77             int port = url.getPort();
78             if (port == -1)
79             {
80                 port = connector.getDefaultPort();
81             }
82             props.put("mail." + protocol + ".port", String.valueOf(port));
83
84             if (secure)
85             {
86                 System.setProperty("mail." + protocol + ".socketFactory.port", String.valueOf(port));
87                 if (protocol.equals("smtp"))
88                 {
89                     // these following properties should not be set
90
// on the System properties as well since they will
91
// conflict with the smtp properties.
92
props = (Properties JavaDoc)props.clone();
93
94                     props.put("mail.smtp.ssl", "true");
95                     props.put("mail.smtp.socketFactory.class", ((SmtpsConnector)connector).getSocketFactory());
96                     props.put("mail.smtp.socketFactory.fallback",
97                         ((SmtpsConnector)connector).getSocketFactoryFallback());
98
99                     if (((SmtpsConnector)connector).getTrustStore() != null)
100                     {
101                         System.setProperty("javax.net.ssl.trustStore",
102                             ((SmtpsConnector)connector).getTrustStore());
103                         if (((SmtpsConnector)connector).getTrustStorePassword() != null)
104                         {
105                             System.setProperty("javax.net.ssl.trustStorePassword",
106                                 ((SmtpsConnector)connector).getTrustStorePassword());
107                         }
108                     }
109                 }
110             }
111             props.setProperty("mail." + protocol + ".rsetbeforequit", "true");
112
113             if (StringUtils.isNotBlank(url.getPassword()))
114             {
115                 props.put("mail." + protocol + ".auth", "true");
116                 Authenticator JavaDoc auth = connector.getAuthenticator();
117                 if (auth == null)
118                 {
119                     auth = new DefaultAuthenticator(url.getUsername(), url.getPassword());
120                     logger.debug("No Authenticator set on Connector: " + connector.getName()
121                                  + ". Using default.");
122                 }
123                 session = Session.getInstance(props, auth);
124             }
125             else
126             {
127                 // reset authentication property so smtp is not affected (MULE-464)
128
props.put("mail." + protocol + ".auth", "false");
129                 session = Session.getInstance(props, null);
130             }
131         }
132
133         return session;
134     }
135
136     public static String JavaDoc internetAddressesToString(InternetAddress JavaDoc[] addresses)
137     {
138         if (addresses == null || addresses.length == 0)
139         {
140             return StringUtils.EMPTY;
141         }
142         StringBuffer JavaDoc buf = new StringBuffer JavaDoc();
143         for (int i = 0; i < addresses.length; i++)
144         {
145             InternetAddress JavaDoc address = addresses[i];
146             buf.append(address.getAddress());
147             // all except the last one
148
if (i < addresses.length - 1)
149             {
150                 buf.append(", ");
151             }
152         }
153         return buf.toString();
154     }
155
156     public static String JavaDoc internetAddressesToString(InternetAddress JavaDoc address)
157     {
158         return internetAddressesToString(new InternetAddress JavaDoc[]{address});
159     }
160
161     public static String JavaDoc mailAddressesToString(Address JavaDoc[] addresses)
162     {
163         if (addresses == null || addresses.length == 0)
164         {
165             return StringUtils.EMPTY;
166         }
167         StringBuffer JavaDoc buf = new StringBuffer JavaDoc();
168         for (int i = 0; i < addresses.length; i++)
169         {
170             Address JavaDoc address = addresses[i];
171             buf.append(address.toString());
172             // all except the last one
173
if (i < addresses.length - 1)
174             {
175                 buf.append(", ");
176             }
177         }
178         return buf.toString();
179     }
180
181     public static String JavaDoc mailAddressesToString(Address JavaDoc address)
182     {
183         return mailAddressesToString(new Address JavaDoc[]{address});
184     }
185
186     public static InternetAddress JavaDoc[] stringToInternetAddresses(String JavaDoc address) throws AddressException JavaDoc
187     {
188         InternetAddress JavaDoc[] inetaddresses;
189         if (StringUtils.isNotBlank(address))
190         {
191             inetaddresses = InternetAddress.parse(address, false);
192         }
193         else
194         {
195             throw new NullPointerException JavaDoc(new org.mule.config.i18n.Message(Messages.X_IS_NULL,
196                 "Email address").toString());
197         }
198         return inetaddresses;
199     }
200
201     /**
202      * DefaultAuthenticator is used to do simple authentication when the SMTP server
203      * requires it.
204      */

205     private static class DefaultAuthenticator extends javax.mail.Authenticator JavaDoc
206     {
207         private String JavaDoc username = null;
208         private String JavaDoc password = null;
209
210         public DefaultAuthenticator(String JavaDoc user, String JavaDoc pwd)
211         {
212             username = user;
213             password = pwd;
214         }
215
216         public PasswordAuthentication JavaDoc getPasswordAuthentication()
217         {
218             return new PasswordAuthentication JavaDoc(username, password);
219         }
220     }
221 }
222
Popular Tags