KickJava   Java API By Example, From Geeks To Geeks.

Java > Open Source Codes > org > apache > fulcrum > template > TemplateEmail


1 package org.apache.fulcrum.template;
2
3 /* ====================================================================
4  * The Apache Software License, Version 1.1
5  *
6  * Copyright (c) 2001 The Apache Software Foundation. All rights
7  * reserved.
8  *
9  * Redistribution and use in source and binary forms, with or without
10  * modification, are permitted provided that the following conditions
11  * are met:
12  *
13  * 1. Redistributions of source code must retain the above copyright
14  * notice, this list of conditions and the following disclaimer.
15  *
16  * 2. Redistributions in binary form must reproduce the above copyright
17  * notice, this list of conditions and the following disclaimer in
18  * the documentation and/or other materials provided with the
19  * distribution.
20  *
21  * 3. The end-user documentation included with the redistribution,
22  * if any, must include the following acknowledgment:
23  * "This product includes software developed by the
24  * Apache Software Foundation (http://www.apache.org/)."
25  * Alternately, this acknowledgment may appear in the software itself,
26  * if and wherever such third-party acknowledgments normally appear.
27  *
28  * 4. The names "Apache" and "Apache Software Foundation" and
29  * "Apache Turbine" must not be used to endorse or promote products
30  * derived from this software without prior written permission. For
31  * written permission, please contact apache@apache.org.
32  *
33  * 5. Products derived from this software may not be called "Apache",
34  * "Apache Turbine", nor may "Apache" appear in their name, without
35  * prior written permission of the Apache Software Foundation.
36  *
37  * THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED OR IMPLIED
38  * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
39  * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
40  * DISCLAIMED. IN NO EVENT SHALL THE APACHE SOFTWARE FOUNDATION OR
41  * ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
42  * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
43  * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF
44  * USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
45  * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
46  * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT
47  * OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
48  * SUCH DAMAGE.
49  * ====================================================================
50  *
51  * This software consists of voluntary contributions made by many
52  * individuals on behalf of the Apache Software Foundation. For more
53  * information on the Apache Software Foundation, please see
54  * <http://www.apache.org/>.
55  */

56
57 import java.io.StringWriter JavaDoc;
58 import java.util.ArrayList JavaDoc;
59 import java.util.Iterator JavaDoc;
60 import java.util.List JavaDoc;
61
62 import javax.mail.internet.InternetAddress JavaDoc;
63
64 import org.apache.commons.lang.WordUtils;
65 import org.apache.commons.mail.SimpleEmail;
66 import org.apache.fulcrum.ServiceException;
67
68 /**
69  * This is a simple class for sending email from within the TemplateService.
70  * Essentially, the body of the email is processed with a
71  * TemplateContext object.
72  * The beauty of this is that you can send email from within your
73  * template layer or from your business logic in your Java code.
74  * The body of the email is just a TemplateService template so you can use
75  * all the template functionality of your TemplateService within your emails!
76  *
77  * <p>Example Usage (This all needs to be on one line in your
78  * template):
79  *
80  * <p>Setup your imports:
81  *
82  * <p>import org.apache.fulcrum.template.TemplateEmail;
83  * <p>import org.apache.turbine.modules.ContextAdapter;
84  *
85  * <p>Setup your context:
86  *
87  * <p>context.put ("TemplateEmail", new TemplateEmail() );
88  * <p>context.put ("contextAdapter", new ContextAdapter(context) );
89  *
90  * <p>Then, in your template (Velocity Example):
91  *
92  * <pre>
93  * $TemplateEmail.setTo("Jon Stevens", "jon@latchkey.com")
94  * .setFrom("Mom", "mom@mom.com").setSubject("Eat dinner")
95  * .setTemplate("email/momEmail.vm")
96  * .setContext($contextAdapter)
97  * </pre>
98  *
99  * The email/momEmail.vm template will then be parsed with the
100  * Context that was defined with setContext().
101  *
102  * <p>If you want to use this class from within your Java code all you
103  * have to do is something like this:
104  *
105  * <p>import org.apache.fulcrum.template.TemplateEmail;
106  * <p>import org.apache.turbine.modules.ContextAdapter;
107  *
108  * <pre>
109  * TemplateEmail ve = new TemplateEmail();
110  * ve.setTo("Jon Stevens", "jon@latchkey.com");
111  * ve.setFrom("Mom", "mom@mom.com").setSubject("Eat dinner");
112  * ve.setContext(new ContextAdapter(context));
113  * ve.setTemplate("email/momEmail.vm")
114  * ve.send();
115  * </pre>
116  *
117  * <p>(Note that when used within a Velocity template, the send method
118  * will be called for you when Velocity tries to convert the
119  * TemplateEmail to a string by calling toString()).</p>
120  *
121  * <p>If you need your email to be word-wrapped, you can add the
122  * following call to those above:
123  *
124  * <pre>
125  * ve.setWordWrap (60);
126  * </pre>
127  *
128  * <p>This class is just a wrapper around the SimpleEmail class.
129  * Thus, it uses the JavaMail API and also depends on having the
130  * mail.host property set in the System.properties().
131  *
132  * @author <a HREF="mailto:jon@latchkey.com">Jon S. Stevens</a>
133  * @author <a HREF="mailto:gcoladonato@yahoo.com">Greg Coladonato</a>
134  * @author <a HREF="mailto:elicia@collab.net">Elicia David</a>
135  * @version $Id: TemplateEmail.java,v 1.1 2004/11/12 10:26:02 epugh Exp $
136  */

137 public class TemplateEmail
138 {
139     /** The to name field. */
140     private String JavaDoc toName = null;
141
142     /** The to email field. */
143     private String JavaDoc toEmail = null;
144
145     /** The from name field. */
146     private String JavaDoc fromName = null;
147
148     /** The from email field. */
149     private String JavaDoc fromEmail = null;
150
151     /** The cc name field. */
152     private String JavaDoc ccName = null;
153
154     /** The cc email field. */
155     private String JavaDoc ccEmail = null;
156
157     /** The subject of the message. */
158     private String JavaDoc subject = null;
159
160     /** The to email list. */
161     private List JavaDoc toList = null;
162
163     /** The cc list. */
164     private List JavaDoc ccList = null;
165
166     /** The cc list. */
167     private List JavaDoc replyToList = null;
168
169     private List JavaDoc headersList;
170
171     /** The column to word-wrap at. <code>0</code> indicates no wrap. */
172     private int wordWrap = 0;
173
174     /**
175      * The template to process, relative to the TemplateService template
176      * directory.
177      */

178     private String JavaDoc template = null;
179
180     /**
181      * A Context
182      */

183     private TemplateContext context = null;
184
185     /**
186      * The charset
187      */

188     private String JavaDoc charset = null;
189
190     /**
191      * Constructor
192      */

193     public TemplateEmail()
194     {
195         this(null);
196     }
197
198     /**
199      * Constructor
200      */

201     public TemplateEmail(TemplateContext context)
202     {
203         this.context = context;
204     }
205
206     public String JavaDoc getCharSet()
207     {
208         return charset;
209     }
210
211     public String JavaDoc getTemplate()
212     {
213         return template;
214     }
215
216     public int getWordWrap()
217     {
218         return wordWrap;
219     }
220
221     public List JavaDoc getToList()
222     {
223         return toList == null ? toList = new ArrayList JavaDoc() : toList;
224     }
225
226     public void setToList(List JavaDoc v)
227     {
228         toList = v;
229     }
230
231     public List JavaDoc getCCList()
232     {
233         return ccList == null ? ccList = new ArrayList JavaDoc() : ccList;
234     }
235
236     public List JavaDoc getReplyToList()
237     {
238         return replyToList == null ? replyToList = new ArrayList JavaDoc(3) : replyToList;
239     }
240
241     public List JavaDoc getHeadersList()
242     {
243         return headersList == null ? headersList = new ArrayList JavaDoc(3) : headersList;
244     }
245
246     public String JavaDoc getToName()
247     {
248         return toName;
249     }
250
251     public String JavaDoc getToEmail()
252     {
253         return toEmail;
254     }
255
256     public String JavaDoc getFromName()
257     {
258         return fromName;
259     }
260
261     public String JavaDoc getFromEmail()
262     {
263         return fromEmail;
264     }
265
266     public String JavaDoc getCCName()
267     {
268         return ccName;
269     }
270
271     public String JavaDoc getCCEmail()
272     {
273         return ccEmail;
274     }
275
276     /** Add a recipient TO to the email.
277      *
278      * @param email A String.
279      * @param name A String.
280      */

281     public void addTo(String JavaDoc email, String JavaDoc name)
282         throws Exception JavaDoc
283     {
284         try
285         {
286             if ((name == null) || (name.trim().equals("")))
287             {
288                 name = email;
289             }
290
291             if (getCharSet() != null)
292             {
293                 getToList().add(new InternetAddress JavaDoc(email, name, getCharSet()));
294             }
295             else
296             {
297                 getToList().add(new InternetAddress JavaDoc(email, name));
298             }
299         }
300         catch (Exception JavaDoc e)
301         {
302             throw new Exception JavaDoc("Cannot add 'To' recipient: " + e);
303         }
304     }
305  
306     /**
307      * Add a recipient CC to the email.
308      *
309      * @param email A String.
310      * @param name A String.
311      */

312     public void addCc(String JavaDoc email, String JavaDoc name)
313         throws Exception JavaDoc
314     {
315         try
316         {
317             if ((name == null) || (name.trim().equals("")))
318             {
319                 name = email;
320             }
321
322             if (getCharSet() != null)
323             {
324                 getCCList().add(new InternetAddress JavaDoc(email, name, getCharSet()));
325             }
326             else
327             {
328                 getCCList().add(new InternetAddress JavaDoc(email, name));
329             }
330         }
331         catch (Exception JavaDoc e)
332         {
333             throw new Exception JavaDoc("Cannot add 'CC' recipient: " + e);
334         }
335     }
336
337
338     /**
339      * The given Unicode string will be charset-encoded using the specified
340      * charset. The charset is also used to set the "charset" parameter.
341      *
342      * @param charset a <code>String</code> value
343      */

344     public void setCharset(String JavaDoc charset)
345     {
346         this.charset = charset;
347     }
348
349     /**
350      * To: name, email
351      *
352      * @param to A String with the TO name.
353      * @param email A String with the TO email.
354      * @return A TemplateEmail (self).
355      */

356     public TemplateEmail setTo(String JavaDoc to,
357                                String JavaDoc email)
358     {
359         this.toName = to;
360         this.toEmail = email;
361         return (this);
362     }
363
364     /**
365      * From: name, email.
366      *
367      * @param from A String with the FROM name.
368      * @param email A String with the FROM email.
369      * @return A TemplateEmail (self).
370      */

371     public TemplateEmail setFrom(String JavaDoc from,
372                                  String JavaDoc email)
373     {
374         this.fromName = from;
375         this.fromEmail = email;
376         return (this);
377     }
378
379     /**
380      * CC: name, email.
381      *
382      * @param from A String with the CC name.
383      * @param email A String with the CC email.
384      * @return A TemplateEmail (self).
385      */

386     public TemplateEmail setCC(String JavaDoc cc,
387                                  String JavaDoc email)
388     {
389         this.ccName = cc;
390         this.ccEmail = email;
391         return (this);
392     }
393
394
395     /**
396      * Add a reply to address to the email.
397      *
398      * @param email A String.
399      * @param name A String.
400      * @return An Email.
401      * @exception MessagingException.
402      */

403     public TemplateEmail addReplyTo( String JavaDoc name, String JavaDoc email)
404     {
405         String JavaDoc[] emailName = new String JavaDoc[2];
406         emailName[0] = email;
407         emailName[1] = name;
408         getReplyToList().add(emailName);
409         return this;
410     }
411
412     public TemplateEmail addHeader(String JavaDoc name, String JavaDoc value)
413     {
414         String JavaDoc[] pair = new String JavaDoc[2];
415         pair[0] = name;
416         pair[1] = value;
417         getHeadersList().add(pair);
418         return this;
419     }
420
421     public String JavaDoc getSubject()
422     {
423         return this.subject;
424     }
425
426     /**
427      * Subject.
428      *
429      * @param subject A String with the subject.
430      * @return A TemplateEmail (self).
431      */

432     public TemplateEmail setSubject(String JavaDoc subject)
433     {
434         if (subject == null)
435         {
436             this.subject = "";
437         }
438         else
439         {
440             this.subject = subject;
441         }
442         return (this);
443     }
444
445     /**
446      * TemplateService template to execute. Path is relative to the
447      * TemplateService templates directory.
448      *
449      * @param template A String with the template.
450      * @return A TemplateEmail (self).
451      */

452     public TemplateEmail setTemplate(String JavaDoc template)
453     {
454         this.template = template;
455         return (this);
456     }
457
458     /**
459      * Set the column at which long lines of text should be word-
460      * wrapped. Setting to zero turns off word-wrap (default).
461      *
462      * NOTE: don't use tabs in your email template document,
463      * or your word-wrapping will be off for the lines with tabs
464      * in them.
465      *
466      * @param wordWrap The column at which to wrap long lines.
467      * @return A TemplateEmail (self).
468      */

469     public TemplateEmail setWordWrap(int wordWrap)
470     {
471         this.wordWrap = wordWrap;
472         return (this);
473     }
474
475     /**
476      * Set the context object that will be merged with the
477      * template.
478      *
479      * @param context A TemplateContext context object.
480      * @return A TemplateEmail (self).
481      */

482     public TemplateEmail setContext(TemplateContext context)
483     {
484         this.context = context;
485         return (this);
486     }
487
488     /**
489      * Get the context object that will be merged with the
490      * template.
491      *
492      * @return A TemplateContext.
493      */

494     public TemplateContext getContext()
495     {
496         return this.context;
497     }
498
499     /**
500      * This method sends the email. It will throw an exception
501      * if the To name or To Email values are null.
502      */

503     public void send()
504         throws Exception JavaDoc
505     {
506         if (getToEmail() == null || getToName() == null)
507         {
508             throw new Exception JavaDoc ("Must set a To:");
509         }
510
511         // this method is only supposed to send to one user (additional cc:
512
// users are ok.)
513
setToList(null);
514         addTo(toEmail, toName);
515         sendMultiple();
516     }
517
518     protected String JavaDoc handleRequest()
519         throws ServiceException
520     {
521         StringWriter JavaDoc sw = new StringWriter JavaDoc();
522         TurbineTemplate.handleRequest(getContext(),getTemplate(),sw);
523         return sw.toString();
524     }
525
526     /**
527      * This method sends the email to multiple addresses.
528      */

529     public void sendMultiple()
530         throws Exception JavaDoc
531     {
532         if (getToList() == null || getToList().isEmpty())
533         {
534             throw new Exception JavaDoc ("Must set a To:");
535         }
536
537         // Process the template.
538
String JavaDoc body = handleRequest();
539
540         // If the caller desires word-wrapping, do it here
541
if (getWordWrap() > 0)
542         {
543             body = WordUtils.wrap(body, getWordWrap());
544         }
545
546         SimpleEmail se = new SimpleEmail();
547         if (getCharSet() != null)
548         {
549             se.setCharset(getCharSet());
550         }
551         se.setFrom(getFromEmail(), getFromName());
552         se.setTo(getToList());
553         if (getCCList() != null && !getCCList().isEmpty())
554         {
555             se.setCc(getCCList());
556         }
557         addReplyTo(se);
558         se.setSubject(getSubject());
559         se.setMsg(body);
560
561         if (getHeadersList() != null)
562         {
563             for (Iterator JavaDoc i = getHeadersList().iterator();i.hasNext();)
564             {
565                 String JavaDoc[] pair = (String JavaDoc[])i.next();
566                 se.addHeader(pair[0], pair[1]);
567             }
568         }
569         
570         se.send();
571     }
572
573     /**
574      * if any reply-to email addresses exist, add them to the SimpleEmail
575      *
576      * @param se a <code>SimpleEmail</code> value
577      * @exception Exception if an error occurs
578      */

579     private void addReplyTo(SimpleEmail se)
580         throws Exception JavaDoc
581     {
582         if (getReplyToList() != null)
583         {
584             for (Iterator JavaDoc i = getReplyToList().iterator();i.hasNext();)
585             {
586                 String JavaDoc[] emailName = (String JavaDoc[])i.next();
587                 se.addReplyTo(emailName[0], emailName[1]);
588             }
589         }
590     }
591
592     /**
593      * The method toString() calls send() for ease of use within a
594      * TemplateService template (see example usage above).
595      *
596      * @return An empty string.
597      */

598     public String JavaDoc toString()
599     {
600         try
601         {
602             send();
603         }
604         catch (Exception JavaDoc e)
605         {
606 // Log.error ("TemplateEmail error", e);
607
}
608         return "";
609     }
610 }
611
Popular Tags