KickJava   Java API By Example, From Geeks To Geeks.

Java > Open Source Codes > com > methodhead > mail > Mail


1 /*
2  * Copyright (C) 2006 Methodhead Software LLC. All rights reserved.
3  *
4  * This file is part of TransferCM.
5  *
6  * TransferCM is free software; you can redistribute it and/or modify it under the
7  * terms of the GNU General Public License as published by the Free Software
8  * Foundation; either version 2 of the License, or (at your option) any later
9  * version.
10  *
11  * TransferCM is distributed in the hope that it will be useful, but WITHOUT ANY
12  * WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
13  * FOR A PARTICULAR PURPOSE. See the GNU General Public License for more
14  * details.
15  *
16  * You should have received a copy of the GNU General Public License along with
17  * TransferCM; if not, write to the Free Software Foundation, Inc., 51 Franklin St,
18  * Fifth Floor, Boston, MA 02110-1301 USA
19  */

20
21 package com.methodhead.mail;
22
23 import java.io.File JavaDoc;
24 import java.util.Properties JavaDoc;
25 import javax.mail.internet.InternetAddress JavaDoc;
26 import javax.mail.internet.AddressException JavaDoc;
27 import org.apache.commons.mail.SimpleEmail;
28 import org.apache.commons.mail.MultiPartEmail;
29 import org.apache.commons.mail.HtmlEmail;
30 import org.apache.commons.mail.EmailException;
31 import org.apache.commons.mail.EmailAttachment;
32 import com.methodhead.MhfException;
33 import org.apache.commons.lang.exception.ExceptionUtils;
34 import org.apache.commons.lang.builder.ToStringBuilder;
35 import org.apache.commons.lang.StringUtils;
36 import org.apache.log4j.Logger;
37
38 /**
39  * Provides simplified interface for sending email messages. This class uses
40  * the Jakarta Commons Email API to send messages.
41  */

42 public class Mail {
43
44   // constructors /////////////////////////////////////////////////////////////
45

46   // constants ////////////////////////////////////////////////////////////////
47

48   // classes //////////////////////////////////////////////////////////////////
49

50   // methods //////////////////////////////////////////////////////////////////
51

52   /**
53    * <p>
54    * Sets the properties that contain configuration parameters.
55    * JavaMail is used to send mail, and these properties are
56    * passed directly to JavaMail classes. The following
57    * properties (and their default values) are important:
58    * </p>
59    * <ul>
60    * <li>mail.host (The local machine)</li>
61    * <li>mail.from (<tt>username@host</tt>)</li>
62    * </ul>
63    * <p>
64    * Find information about all setting in Appendix A of the
65    * JavaMail API Design Specification.
66    * </p>
67    */

68   public static void init(
69     Properties JavaDoc props ) {
70
71     if ( logger_.isDebugEnabled() ) {
72       logger_.debug(
73         "Initializing with properties " +
74         new ToStringBuilder( props ).
75           append( "mail.host", props.get( "mail.host" ) ).
76           append( "mail.from", props.get( "mail.from" ) ).
77           toString() );
78     }
79
80     mailProperties_ = props;
81   }
82
83   /**
84    * Instantiates and initializes a new <tt>SimpleEmail</tt> (not unit tested).
85    */

86   public static SimpleEmail newSimpleEmail() {
87
88     SimpleEmail email = new SimpleEmail();
89     email.setHostName( mailProperties_.getProperty( "mail.host" ) );
90     return email;
91   }
92
93   /**
94    * Instantiates and initializes a new <tt>MultiPartEmail</tt> (not unit
95    * tested).
96    */

97   public static MultiPartEmail newMultiPartEmail() {
98
99     MultiPartEmail email = new MultiPartEmail();
100     email.setHostName( mailProperties_.getProperty( "mail.host" ) );
101     return email;
102   }
103
104   /**
105    * Instantiates and initializes a new <tt>HtmlEmail</tt> (not unit tested).
106    */

107   public static HtmlEmail newHtmlEmail() {
108
109     HtmlEmail email = new HtmlEmail();
110     email.setHostName( mailProperties_.getProperty( "mail.host" ) );
111     return email;
112   }
113
114   /**
115    * Utility method to validate an email address.
116    */

117   protected static boolean isValidAddress(
118     String JavaDoc address ) {
119
120     if ( address == null )
121       return false;
122
123     try {
124       InternetAddress JavaDoc ia = new InternetAddress JavaDoc( address );
125       ia.validate();
126     }
127     catch ( AddressException JavaDoc e ) {
128       return false;
129     }
130
131     return true;
132   }
133
134   /**
135    * Sends <tt>text</tt> with <tt>subject</tt> to each email address in
136    * <tt>to</tt>. Any invalid email addresses in <tt>to</tt> are ignored, but
137    * an invalid <tt>from</tt> address will throw an exception.
138    * <strong>Note:</strong> Each message is sent individually; be aware of the
139    * load on your mail server.
140    */

141   public static void send(
142     String JavaDoc[] to,
143     String JavaDoc from,
144     String JavaDoc subject,
145     String JavaDoc text ) {
146
147     if ( logger_.isDebugEnabled() ) {
148       logger_.debug( "Sending plain text email from " + from + " with subject \"" + subject + "\", " + text.length() + " characters in body." );
149     }
150
151     try {
152       for ( int i = 0; i < to.length; i++ ) {
153         if ( isValidAddress( to[ i ] ) ) {
154
155           if ( logger_.isDebugEnabled() ) {
156             logger_.debug( "Sending message to " + to[ i ] );
157           }
158
159           SimpleEmail email = newSimpleEmail();
160           email.addTo( to[ i ] );
161           email.setFrom( from );
162           email.setSubject( subject );
163           email.setMsg( text );
164           email.send();
165         }
166         else {
167           if ( logger_.isDebugEnabled() ) {
168             logger_.debug( "Skipping invalid email address " + to[ i ] );
169           }
170         }
171       }
172     }
173     catch ( EmailException e ) {
174       String JavaDoc msg =
175         "Sending plain text email from " + from + " with subject \"" + subject + "\", " + text.length() + " characters in body.\n" +
176         ExceptionUtils.getStackTrace( e );
177       logger_.error( msg );
178       throw new MhfException( msg );
179     }
180   }
181
182   /**
183    * Sends <tt>text</tt> with <tt>subject</tt> to <tt>to</tt>. If <tt>to</tt>
184    * is invalid, no email is sent, but an invalid <tt>from</tt> address will
185    * throw an exception.
186    */

187   public static void send(
188     String JavaDoc to,
189     String JavaDoc from,
190     String JavaDoc subject,
191     String JavaDoc text )
192   throws
193     EmailException {
194
195     send( new String JavaDoc[] { to }, from, subject, text );
196   }
197
198   /**
199    * Sends <tt>text</tt> and <tt>html</tt> with <tt>subject</tt> to each email
200    * address in <tt>to</tt>. Any invalid email addresses in <tt>to</tt> are
201    * ignored, but an invalid <tt>from</tt> address will throw an
202    * exception. <strong>Note:</strong> Each message is sent
203    * individually; be aware of the load on your mail server.
204    */

205   public static void send(
206     String JavaDoc[] to,
207     String JavaDoc from,
208     String JavaDoc subject,
209     String JavaDoc text,
210     String JavaDoc html ) {
211
212     send( to, from, subject, text, html, new File JavaDoc[] {} );
213   }
214
215   /**
216    * Sends <tt>text</tt> with <tt>subject</tt> and <tt>attachments</tt> to each
217    * email address in <tt>to</tt>. Any invalid email addresses in <tt>to</tt>
218    * are ignored, but an invalid <tt>from</tt> address will throw an
219    * exception. A null or non-existant file in attachments
220    * will throw a <tt>MessagingException</tt>. <strong>Note:</strong> Each
221    * message is sent individually; be aware of the load on your mail server.
222    */

223   public static void send(
224     String JavaDoc[] to,
225     String JavaDoc from,
226     String JavaDoc subject,
227     String JavaDoc text,
228     File JavaDoc[] attachments ) {
229
230     send( to, from, subject, text, null, attachments );
231   }
232
233   /**
234    * Sends <tt>text</tt> and <tt>html</tt> with <tt>subject</tt> and
235    * <tt>attachments</tt> to each email address in <tt>to</tt>. If
236    * <tt>html</tt> is <tt>null</tt>, a text-only email is sent. Any invalid
237    * email addresses in <tt>to</tt> are ignored, but an invalid <tt>from</tt>
238    * address will throw an exception. A null or non-existant
239    * file in attachments will throw a <tt>MessagingException</tt>.
240    * <strong>Note:</strong> Each message is sent individually; be aware of the
241    * load on your mail server.
242    */

243   public static void send(
244     String JavaDoc[] to,
245     String JavaDoc from,
246     String JavaDoc subject,
247     String JavaDoc text,
248     String JavaDoc html,
249     File JavaDoc[] attachments ) {
250
251     if ( logger_.isDebugEnabled() ) {
252       String JavaDoc textInfo = "no text";
253       if ( text != null ) {
254         textInfo = "" + text.length() + " characters in text body";
255       }
256
257       String JavaDoc htmlInfo = "no html";
258       if ( html != null ) {
259         htmlInfo = "" + html.length() + " characters in html body";
260       }
261
262       logger_.debug(
263         "Sending html email from " + from + " with subject \"" + subject + "\", " + textInfo + ", " +
264         htmlInfo + ", and attachments " + StringUtils.join( attachments ) );
265     }
266
267     try {
268       if ( attachments == null )
269         throw new EmailException( "Attachments array is null." );
270
271       //
272
// create EmailAttachments
273
//
274
EmailAttachment[] emailAttachments =
275         new EmailAttachment[ attachments.length ];
276
277       for ( int i = 0; i < attachments.length; i++ ) {
278
279         //
280
// valid attachment?
281
//
282
if (
283           ( attachments[ i ] == null ) ||
284           !attachments[ i ].exists() ||
285           !attachments[ i ].isFile() )
286
287           throw new EmailException(
288             "Attachment \"" + attachments[ i ] +
289             "\" does not exist or is not a file." );
290
291         emailAttachments[ i ] = new EmailAttachment();
292         emailAttachments[ i ].setPath( attachments[ i ].getAbsolutePath() );
293       }
294
295       for ( int i = 0; i < to.length; i++ ) {
296
297         if ( isValidAddress( to[ i ] ) ) {
298
299           if ( logger_.isDebugEnabled() ) {
300             logger_.debug( "Sending to " + to[ i ] );
301           }
302
303           HtmlEmail email = newHtmlEmail();
304           email.addTo( to[ i ] );
305           email.setFrom( from );
306           email.setSubject( subject );
307
308           if ( text != null )
309             email.setTextMsg( text );
310
311           if ( html != null )
312             email.setHtmlMsg( html );
313
314           //
315
// add attachments
316
//
317
for ( int j = 0; j < emailAttachments.length; j++ )
318             email.attach( emailAttachments[ j ] );
319
320           email.send();
321         }
322         else {
323           if ( logger_.isDebugEnabled() ) {
324             logger_.debug( "Skipping invalid email address " + to[ i ] );
325           }
326         }
327       }
328     }
329     catch ( EmailException e ) {
330       String JavaDoc msg =
331         "Sending html email from " + from + " to " + to +
332         " with subject \"" + subject + "\", text \"" + text + "\", html \"" +
333         html + "\", and attachments " + attachments + "\n" +
334         ExceptionUtils.getStackTrace( e );
335       logger_.error( msg );
336       throw new MhfException( msg );
337     }
338   }
339
340   // properties ///////////////////////////////////////////////////////////////
341

342
343   // attributes ///////////////////////////////////////////////////////////////
344

345   protected static Properties JavaDoc mailProperties_ = new Properties JavaDoc();
346
347   private static Logger logger_ = Logger.getLogger( Mail.class );
348 }
349
Popular Tags