KickJava   Java API By Example, From Geeks To Geeks.

Java > Open Source Codes > org > oddjob > dummy > DummyEmailTask


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

54 package org.oddjob.dummy;
55
56 // Ant imports
57

58 import java.io.File JavaDoc;
59 import java.util.Enumeration JavaDoc;
60 import java.util.StringTokenizer JavaDoc;
61 import java.util.Vector JavaDoc;
62 import org.apache.tools.ant.BuildException;
63 import org.apache.tools.ant.DirectoryScanner;
64 import org.apache.tools.ant.Project;
65 import org.apache.tools.ant.Task;
66 import org.apache.tools.ant.taskdefs.email.EmailAddress;
67 import org.apache.tools.ant.taskdefs.email.Message;
68 import org.apache.tools.ant.types.EnumeratedAttribute;
69 import org.apache.tools.ant.types.FileSet;
70
71 /**
72  * A task to send SMTP email. This is a refactoring of the SendMail and
73  * MimeMail tasks such that both are within a single task.
74  *
75  * @author Magesh Umasankar
76  * @author glenn_twiggs@bmc.com
77  * @author steve_l@iseran.com steve loughran
78  * @author ehatcher@apache.org Erik Hatcher
79  * @author paulo.gaspar@krankikom.de Paulo Gaspar
80  * @author roxspring@imapmail.org Rob Oxspring
81  * @author <a HREF="mailto:ishu@akm.ru">Aleksandr Ishutin</a>
82  * @author <a HREF="mailto:levylambert@tiscali-dsl.de">Antoine Levy-Lambert</a>
83  * @since Ant 1.5
84  * @ant.task name="mail" category="network"
85  */

86 public class DummyEmailTask
87      extends Task {
88     /** Constant to show that the best available mailer should be used. */
89     public static final String JavaDoc AUTO = "auto";
90     /** Constant to allow the Mime mailer to be requested */
91     public static final String JavaDoc MIME = "mime";
92     /** Constant to allow the UU mailer to be requested */
93     public static final String JavaDoc UU = "uu";
94     /** Constant to allow the plaintext mailer to be requested */
95     public static final String JavaDoc PLAIN = "plain";
96
97
98     /**
99      * Enumerates the encoding constants
100      */

101     public static class Encoding extends EnumeratedAttribute {
102         /**
103          * finds the valid encoding values
104          *
105          * @return a list of valid entries
106          */

107         public String JavaDoc[] getValues() {
108             return new String JavaDoc[] {AUTO, MIME, UU, PLAIN};
109         }
110     }
111
112     private String JavaDoc encoding = AUTO;
113     /** host running SMTP */
114     private String JavaDoc host = "localhost";
115     private int port = 25;
116     /** subject field */
117     private String JavaDoc subject = null;
118     /** any text */
119     private Message message = null;
120     /** failure flag */
121     private boolean failOnError = true;
122     private boolean includeFileNames = false;
123     private String JavaDoc messageMimeType = null;
124     /** special headers */
125     /** sender */
126     private EmailAddress from = null;
127     /** replyto */
128     private Vector JavaDoc replyToList = new Vector JavaDoc();
129     /** TO recipients */
130     private Vector JavaDoc toList = new Vector JavaDoc();
131     /** CC (Carbon Copy) recipients */
132     private Vector JavaDoc ccList = new Vector JavaDoc();
133     /** BCC (Blind Carbon Copy) recipients */
134     private Vector JavaDoc bccList = new Vector JavaDoc();
135
136     /** file list */
137     private Vector JavaDoc files = new Vector JavaDoc();
138     private Vector JavaDoc filesets = new Vector JavaDoc();
139     /** Character set for MimeMailer*/
140     private String JavaDoc charset = null;
141     /** User for SMTP auth */
142     private String JavaDoc user = null;
143     /** Password for SMTP auth */
144     private String JavaDoc password = null;
145     /** indicate if the user wishes SSL-TLS */
146     private boolean SSL = false;
147
148     /**
149      * sets the user for SMTP auth; this requires JavaMail
150      * @param user
151      * @since ant 1.6
152      */

153     public void setUser(String JavaDoc user) {
154         this.user = user;
155     }
156
157     /**
158      * sets the password for SMTP auth; this requires JavaMail
159      * @param password
160      * @since ant 1.6
161      */

162     public void setPassword(String JavaDoc password) {
163         this.password = password;
164     }
165
166     /**
167      * tells if the user needs to send his data over SSL
168      * @param SSL
169      * @since ant 1.6
170      */

171     public void setSSL(boolean SSL) {
172         this.SSL = SSL;
173     }
174
175     /**
176      * Allows the build writer to choose the preferred encoding method
177      *
178      * @param encoding The encoding (one of AUTO,MIME,UU,PLAIN)
179      */

180     public void setEncoding(Encoding encoding) {
181         this.encoding = encoding.getValue();
182     }
183
184
185     /**
186      * Sets the mail server port
187      *
188      * @param port The port to use
189      */

190     public void setMailport(int port) {
191         this.port = port;
192     }
193
194
195     /**
196      * Sets the host
197      *
198      * @param host The host to connect to
199      */

200     public void setMailhost(String JavaDoc host) {
201         this.host = host;
202     }
203
204
205     /**
206      * Sets the subject line of the email
207      *
208      * @param subject Subject of this email.
209      */

210     public void setSubject(String JavaDoc subject) {
211         this.subject = subject;
212     }
213
214
215     /**
216      * Shorthand method to set the message
217      *
218      * @param message Message body of this email.
219      */

220     public void setMessage(String JavaDoc message) {
221         if (this.message != null) {
222             throw new BuildException("Only one message can be sent in an "
223                  + "email");
224         }
225
226         this.message = new Message(message);
227         this.message.setProject(getProject());
228     }
229
230
231     /**
232      * Shorthand method to set the message from a file
233      *
234      * @param file The file from which to take the message
235      */

236     public void setMessageFile(File JavaDoc file) {
237         if (this.message != null) {
238             throw new BuildException("Only one message can be sent in an "
239                  + "email");
240         }
241
242         this.message = new Message(file);
243         this.message.setProject(getProject());
244     }
245
246
247     /**
248      * Shorthand method to set type of the text message, text/plain by default
249      * but text/html or text/xml is quite feasible.
250      *
251      * @param type The new MessageMimeType value
252      */

253     public void setMessageMimeType(String JavaDoc type) {
254         this.messageMimeType = type;
255     }
256
257
258     /**
259      * Add a message element
260      *
261      * @param message The message object
262      * @throws BuildException if a message has already been added
263      */

264     public void addMessage(Message message)
265          throws BuildException {
266         if (this.message != null) {
267             throw new BuildException("Only one message can be sent in an "
268                  + "email");
269         }
270
271         this.message = message;
272     }
273
274
275     /**
276      * Adds a from address element
277      *
278      * @param address The address to send from
279      */

280     public void addFrom(EmailAddress address) {
281         if (this.from != null) {
282             throw new BuildException("Emails can only be from one address");
283         }
284
285         this.from = address;
286     }
287
288
289     /**
290      * Shorthand to set the from address element
291      *
292      * @param address The address to send mail from
293      */

294     public void setFrom(String JavaDoc address) {
295         if (this.from != null) {
296             throw new BuildException("Emails can only be from one address");
297         }
298
299         this.from = new EmailAddress(address);
300     }
301
302
303     /**
304      * Adds a replyto address element
305      *
306      * @param address The address to reply to
307      * @since ant 1.6
308      */

309     public void addReplyTo(EmailAddress address) {
310         this.replyToList.add(address);
311     }
312
313
314     /**
315      * Shorthand to set the replyto address element
316      *
317      * @param address The address to which replies should be directed
318      * @since ant 1.6
319      */

320     public void setReplyTo(String JavaDoc address) {
321         this.replyToList.add(new EmailAddress(address));
322     }
323
324
325     /**
326      * Adds a to address element
327      *
328      * @param address An email address
329      */

330     public void addTo(EmailAddress address) {
331         toList.addElement(address);
332     }
333
334
335     /**
336      * Adds "to" address elements
337      *
338      * @param list Comma separated list of addresses
339      */

340     public void setToList(String JavaDoc list) {
341         StringTokenizer JavaDoc tokens = new StringTokenizer JavaDoc(list, ",");
342
343         while (tokens.hasMoreTokens()) {
344             toList.addElement(new EmailAddress(tokens.nextToken()));
345         }
346     }
347
348
349     /**
350      * Adds "cc" address element
351      *
352      * @param address The email address
353      */

354     public void addCc(EmailAddress address) {
355         ccList.addElement(address);
356     }
357
358
359     /**
360      * Adds "cc" address elements
361      *
362      * @param list Comma separated list of addresses
363      */

364     public void setCcList(String JavaDoc list) {
365         StringTokenizer JavaDoc tokens = new StringTokenizer JavaDoc(list, ",");
366
367         while (tokens.hasMoreTokens()) {
368             ccList.addElement(new EmailAddress(tokens.nextToken()));
369         }
370     }
371
372
373     /**
374      * Adds "bcc" address elements
375      *
376      * @param address The email address
377      */

378     public void addBcc(EmailAddress address) {
379         bccList.addElement(address);
380     }
381
382
383     /**
384      * Adds "bcc" address elements
385      *
386      * @param list comma separated list of addresses
387      */

388     public void setBccList(String JavaDoc list) {
389         StringTokenizer JavaDoc tokens = new StringTokenizer JavaDoc(list, ",");
390
391         while (tokens.hasMoreTokens()) {
392             bccList.addElement(new EmailAddress(tokens.nextToken()));
393         }
394     }
395
396
397     /**
398      * Indicates whether BuildExceptions should be passed back to the core
399      *
400      * @param failOnError The new FailOnError value
401      */

402     public void setFailOnError(boolean failOnError) {
403         this.failOnError = failOnError;
404     }
405
406
407     /**
408      * Adds a list of files to be attached
409      *
410      * @param filenames Comma separated list of files
411      */

412     public void setFiles(String JavaDoc filenames) {
413         StringTokenizer JavaDoc t = new StringTokenizer JavaDoc(filenames, ", ");
414
415         while (t.hasMoreTokens()) {
416             files.addElement(getProject().resolveFile(t.nextToken()));
417         }
418     }
419
420
421     /**
422      * Adds a set of files (nested fileset attribute).
423      *
424      * @param fs The fileset
425      */

426     public void addFileset(FileSet fs) {
427         filesets.addElement(fs);
428     }
429
430
431     /**
432      * Sets Includefilenames attribute
433      *
434      * @param includeFileNames Whether to include filenames in the text of the
435      * message
436      */

437     public void setIncludefilenames(boolean includeFileNames) {
438         this.includeFileNames = includeFileNames;
439     }
440
441
442     /**
443      * Identifies whether file names should be included
444      *
445      * @return Identifies whether file names should be included
446      */

447     public boolean getIncludeFileNames() {
448         return includeFileNames;
449     }
450
451
452     /** Sends an email */
453     public void execute() {
454         Message savedMessage = message;
455         Vector JavaDoc savedFiles = (Vector JavaDoc) files.clone();
456
457         try {
458
459             // a valid message is required
460
if (message == null) {
461                 message = new Message();
462                 message.setProject(getProject());
463             }
464
465             // an address to send from is required
466
if (from == null || from.getAddress() == null) {
467                 throw new BuildException("A from element is required");
468             }
469
470             // at least one address to send to/cc/bcc is required
471
if (toList.isEmpty() && ccList.isEmpty() && bccList.isEmpty()) {
472                 throw new BuildException("At least one of to,cc or bcc must "
473                      + "be supplied");
474             }
475
476             // set the mimetype if not done already (and required)
477
if (messageMimeType != null) {
478                 if (message.isMimeTypeSpecified()) {
479                     throw new BuildException("The mime type can only be "
480                          + "specified in one location");
481                 } else {
482                     message.setMimeType(messageMimeType);
483                 }
484             }
485             // set the character set if not done already (and required)
486
if (charset != null) {
487                 if (message.getCharset() != null) {
488                     throw new BuildException("The charset can only be "
489                          + "specified in one location");
490                 } else {
491                     message.setCharset(charset);
492                 }
493             }
494
495             // identify which files should be attached
496
Enumeration JavaDoc e = filesets.elements();
497
498             while (e.hasMoreElements()) {
499                 FileSet fs = (FileSet) e.nextElement();
500
501                 DirectoryScanner ds = fs.getDirectoryScanner(getProject());
502                 String JavaDoc[] includedFiles = ds.getIncludedFiles();
503                 File JavaDoc baseDir = ds.getBasedir();
504
505                 for (int j = 0; j < includedFiles.length; ++j) {
506                     File JavaDoc file = new File JavaDoc(baseDir, includedFiles[j]);
507
508                     files.addElement(file);
509                 }
510             }
511
512             // let the user know what's going to happen
513
log("Sending email: " + subject, Project.MSG_INFO);
514             log("From " + from, Project.MSG_VERBOSE);
515             log("ReplyTo " + replyToList, Project.MSG_VERBOSE);
516             log("To " + toList, Project.MSG_VERBOSE);
517             log("Cc " + ccList, Project.MSG_VERBOSE);
518             log("Bcc " + bccList, Project.MSG_VERBOSE);
519
520             // let the user know what happened
521
int count = files.size();
522
523             log("Sent email with " + count + " attachment"
524                  + (count == 1 ? "" : "s"), Project.MSG_INFO);
525         } catch (BuildException e) {
526             log("Failed to send email", Project.MSG_WARN);
527             if (failOnError) {
528                 throw e;
529             }
530         } catch (Exception JavaDoc e) {
531           log("Failed to send email", Project.MSG_WARN);
532           if (failOnError) {
533             throw new BuildException(e);
534           }
535         } finally {
536             message = savedMessage;
537             files = savedFiles;
538         }
539     }
540     /**
541      * Sets the character set of mail message.
542      * Will be ignored if mimeType contains ....; Charset=... substring or
543      * encoding is not a <code>mime</code>
544      * @since Ant 1.6
545      */

546     public void setCharset(String JavaDoc charset) {
547       this.charset = charset;
548     }
549     /**
550      * Returns the character set of mail message.
551      *
552      * @return Charset of mail message.
553      * @since Ant 1.6
554      */

555     public String JavaDoc getCharset() {
556       return charset;
557     }
558 }
559
560
Popular Tags