KickJava   Java API By Example, From Geeks To Geeks.

Java > Open Source Codes > org > apache > tools > ant > taskdefs > email > EmailTask


1 /*
2  * Licensed to the Apache Software Foundation (ASF) under one or more
3  * contributor license agreements. See the NOTICE file distributed with
4  * this work for additional information regarding copyright ownership.
5  * The ASF licenses this file to You under the Apache License, Version 2.0
6  * (the "License"); you may not use this file except in compliance with
7  * the License. You may obtain a copy of the License at
8  *
9  * http://www.apache.org/licenses/LICENSE-2.0
10  *
11  * Unless required by applicable law or agreed to in writing, software
12  * distributed under the License is distributed on an "AS IS" BASIS,
13  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14  * See the License for the specific language governing permissions and
15  * limitations under the License.
16  *
17  */

18 package org.apache.tools.ant.taskdefs.email;
19
20 import java.io.File JavaDoc;
21 import java.util.Iterator JavaDoc;
22 import java.util.StringTokenizer JavaDoc;
23 import java.util.Vector JavaDoc;
24
25 import org.apache.tools.ant.BuildException;
26 import org.apache.tools.ant.Project;
27 import org.apache.tools.ant.Task;
28 import org.apache.tools.ant.types.EnumeratedAttribute;
29 import org.apache.tools.ant.types.FileSet;
30 import org.apache.tools.ant.types.Path;
31 import org.apache.tools.ant.types.resources.FileResource;
32 import org.apache.tools.ant.util.ClasspathUtils;
33
34 /**
35  * A task to send SMTP email. This is a refactoring of the SendMail and
36  * MimeMail tasks such that both are within a single task.
37  *
38  * @since Ant 1.5
39  * @ant.task name="mail" category="network"
40  */

41 public class EmailTask extends Task {
42     /** Constant to show that the best available mailer should be used. */
43     public static final String JavaDoc AUTO = "auto";
44     /** Constant to allow the Mime mailer to be requested */
45     public static final String JavaDoc MIME = "mime";
46     /** Constant to allow the UU mailer to be requested */
47     public static final String JavaDoc UU = "uu";
48     /** Constant to allow the plaintext mailer to be requested */
49     public static final String JavaDoc PLAIN = "plain";
50
51     /**
52      * Enumerates the encoding constants.
53      */

54     public static class Encoding extends EnumeratedAttribute {
55         /**
56          * finds the valid encoding values
57          *
58          * @return a list of valid entries
59          */

60         public String JavaDoc[] getValues() {
61             return new String JavaDoc[] {AUTO, MIME, UU, PLAIN};
62         }
63     }
64
65     private String JavaDoc encoding = AUTO;
66     /** host running SMTP */
67     private String JavaDoc host = "localhost";
68     private int port = 25;
69     /** subject field */
70     private String JavaDoc subject = null;
71     /** any text */
72     private Message message = null;
73     /** failure flag */
74     private boolean failOnError = true;
75     private boolean includeFileNames = false;
76     private String JavaDoc messageMimeType = null;
77     /* special headers */
78     /** sender */
79     private EmailAddress from = null;
80     /** replyto */
81     private Vector JavaDoc replyToList = new Vector JavaDoc();
82     /** TO recipients */
83     private Vector JavaDoc toList = new Vector JavaDoc();
84     /** CC (Carbon Copy) recipients */
85     private Vector JavaDoc ccList = new Vector JavaDoc();
86     /** BCC (Blind Carbon Copy) recipients */
87     private Vector JavaDoc bccList = new Vector JavaDoc();
88
89     /** generic headers */
90     private Vector JavaDoc headers = new Vector JavaDoc();
91
92     /** file list */
93     private Path attachments = null;
94     /** Character set for MimeMailer*/
95     private String JavaDoc charset = null;
96     /** User for SMTP auth */
97     private String JavaDoc user = null;
98     /** Password for SMTP auth */
99     private String JavaDoc password = null;
100     /** indicate if the user wishes SSL-TLS */
101     private boolean ssl = false;
102
103     /**
104      * Set the user for SMTP auth; this requires JavaMail.
105      * @param user the String username.
106      * @since Ant 1.6
107      */

108     public void setUser(String JavaDoc user) {
109         this.user = user;
110     }
111
112     /**
113      * Set the password for SMTP auth; this requires JavaMail.
114      * @param password the String password.
115      * @since Ant 1.6
116      */

117     public void setPassword(String JavaDoc password) {
118         this.password = password;
119     }
120
121     /**
122      * Set whether to send data over SSL.
123      * @param ssl boolean; if true SSL will be used.
124      * @since Ant 1.6
125      */

126     public void setSSL(boolean ssl) {
127         this.ssl = ssl;
128     }
129
130     /**
131      * Set the preferred encoding method.
132      *
133      * @param encoding The encoding (one of AUTO, MIME, UU, PLAIN).
134      */

135     public void setEncoding(Encoding encoding) {
136         this.encoding = encoding.getValue();
137     }
138
139     /**
140      * Set the mail server port.
141      *
142      * @param port The port to use.
143      */

144     public void setMailport(int port) {
145         this.port = port;
146     }
147
148     /**
149      * Set the host.
150      *
151      * @param host The host to connect to.
152      */

153     public void setMailhost(String JavaDoc host) {
154         this.host = host;
155     }
156
157     /**
158      * Set the subject line of the email.
159      *
160      * @param subject Subject of this email.
161      */

162     public void setSubject(String JavaDoc subject) {
163         this.subject = subject;
164     }
165
166     /**
167      * Shorthand method to set the message.
168      *
169      * @param message Message body of this email.
170      */

171     public void setMessage(String JavaDoc message) {
172         if (this.message != null) {
173             throw new BuildException("Only one message can be sent in an "
174                  + "email");
175         }
176         this.message = new Message(message);
177         this.message.setProject(getProject());
178     }
179
180     /**
181      * Shorthand method to set the message from a file.
182      *
183      * @param file The file from which to take the message.
184      */

185     public void setMessageFile(File JavaDoc file) {
186         if (this.message != null) {
187             throw new BuildException("Only one message can be sent in an "
188                  + "email");
189         }
190         this.message = new Message(file);
191         this.message.setProject(getProject());
192     }
193
194     /**
195      * Shorthand method to set type of the text message, text/plain by default
196      * but text/html or text/xml is quite feasible.
197      *
198      * @param type The new MessageMimeType value.
199      */

200     public void setMessageMimeType(String JavaDoc type) {
201         this.messageMimeType = type;
202     }
203
204     /**
205      * Add a message element.
206      *
207      * @param message The message object.
208      * @throws BuildException if a message has already been added.
209      */

210     public void addMessage(Message message) throws BuildException {
211         if (this.message != null) {
212             throw new BuildException(
213                 "Only one message can be sent in an email");
214         }
215         this.message = message;
216     }
217
218     /**
219      * Add a from address element.
220      *
221      * @param address The address to send from.
222      */

223     public void addFrom(EmailAddress address) {
224         if (this.from != null) {
225             throw new BuildException("Emails can only be from one address");
226         }
227         this.from = address;
228     }
229
230     /**
231      * Shorthand to set the from address element.
232      *
233      * @param address The address to send mail from.
234      */

235     public void setFrom(String JavaDoc address) {
236         if (this.from != null) {
237             throw new BuildException("Emails can only be from one address");
238         }
239         this.from = new EmailAddress(address);
240     }
241
242     /**
243      * Add a replyto address element.
244      *
245      * @param address The address to reply to.
246      * @since Ant 1.6
247      */

248     public void addReplyTo(EmailAddress address) {
249         this.replyToList.add(address);
250     }
251
252     /**
253      * Shorthand to set the replyto address element.
254      *
255      * @param address The address to which replies should be directed.
256      * @since Ant 1.6
257      */

258     public void setReplyTo(String JavaDoc address) {
259         this.replyToList.add(new EmailAddress(address));
260     }
261
262     /**
263      * Add a to address element.
264      *
265      * @param address An email address.
266      */

267     public void addTo(EmailAddress address) {
268         toList.addElement(address);
269     }
270
271     /**
272      * Shorthand to set the "to" address element.
273      *
274      * @param list Comma-separated list of addresses.
275      */

276     public void setToList(String JavaDoc list) {
277         StringTokenizer JavaDoc tokens = new StringTokenizer JavaDoc(list, ",");
278
279         while (tokens.hasMoreTokens()) {
280             toList.addElement(new EmailAddress(tokens.nextToken()));
281         }
282     }
283
284     /**
285      * Add a "cc" address element.
286      *
287      * @param address The email address.
288      */

289     public void addCc(EmailAddress address) {
290         ccList.addElement(address);
291     }
292
293     /**
294      * Shorthand to set the "cc" address element.
295      *
296      * @param list Comma separated list of addresses.
297      */

298     public void setCcList(String JavaDoc list) {
299         StringTokenizer JavaDoc tokens = new StringTokenizer JavaDoc(list, ",");
300
301         while (tokens.hasMoreTokens()) {
302             ccList.addElement(new EmailAddress(tokens.nextToken()));
303         }
304     }
305
306     /**
307      * Add a "bcc" address element.
308      *
309      * @param address The email address.
310      */

311     public void addBcc(EmailAddress address) {
312         bccList.addElement(address);
313     }
314
315     /**
316      * Shorthand to set the "bcc" address element.
317      *
318      * @param list comma separated list of addresses.
319      */

320     public void setBccList(String JavaDoc list) {
321         StringTokenizer JavaDoc tokens = new StringTokenizer JavaDoc(list, ",");
322
323         while (tokens.hasMoreTokens()) {
324             bccList.addElement(new EmailAddress(tokens.nextToken()));
325         }
326     }
327
328     /**
329      * Set whether BuildExceptions should be passed back to the core.
330      *
331      * @param failOnError The new FailOnError value.
332      */

333     public void setFailOnError(boolean failOnError) {
334         this.failOnError = failOnError;
335     }
336
337     /**
338      * Set the list of files to be attached.
339      *
340      * @param filenames Comma-separated list of files.
341      */

342     public void setFiles(String JavaDoc filenames) {
343         StringTokenizer JavaDoc t = new StringTokenizer JavaDoc(filenames, ", ");
344
345         while (t.hasMoreTokens()) {
346             createAttachments()
347                 .add(new FileResource(getProject().resolveFile(t.nextToken())));
348         }
349     }
350
351     /**
352      * Add a set of files (nested fileset attribute).
353      *
354      * @param fs The fileset.
355      */

356     public void addFileset(FileSet fs) {
357         createAttachments().add(fs);
358     }
359
360     /**
361      * Creates a Path as container for attachments. Supports any
362      * filesystem resource-collections that way.
363      * @return the path to be configured.
364      * @since Ant 1.7
365      */

366     public Path createAttachments() {
367         if (attachments == null) {
368             attachments = new Path(getProject());
369         }
370         return attachments.createPath();
371     }
372
373     /**
374      * Create a nested header element.
375      * @return a Header instance.
376      */

377     public Header createHeader() {
378         Header h = new Header();
379         headers.add(h);
380         return h;
381     }
382
383     /**
384      * Set whether to include filenames.
385      *
386      * @param includeFileNames Whether to include filenames in the text of the
387      * message.
388      */

389     public void setIncludefilenames(boolean includeFileNames) {
390         this.includeFileNames = includeFileNames;
391     }
392
393     /**
394      * Get whether file names should be included.
395      *
396      * @return Identifies whether file names should be included.
397      */

398     public boolean getIncludeFileNames() {
399         return includeFileNames;
400     }
401
402     /**
403      * Send an email.
404      */

405     public void execute() {
406         Message savedMessage = message;
407
408         try {
409             Mailer mailer = null;
410
411             // prepare for the auto select mechanism
412
boolean autoFound = false;
413             // try MIME format
414
if (encoding.equals(MIME)
415                  || (encoding.equals(AUTO) && !autoFound)) {
416                 try {
417                     mailer = (Mailer) ClasspathUtils.newInstance(
418                             "org.apache.tools.ant.taskdefs.email.MimeMailer",
419                             EmailTask.class.getClassLoader(), Mailer.class);
420                     autoFound = true;
421                     log("Using MIME mail", Project.MSG_VERBOSE);
422                 } catch (BuildException e) {
423                     Throwable JavaDoc t = e.getCause() == null ? e : e.getCause();
424                     log("Failed to initialise MIME mail: " + t.getMessage(),
425                             Project.MSG_WARN);
426                     return;
427                 }
428             }
429             // SMTP auth only allowed with MIME mail
430
if (!autoFound && ((user != null) || (password != null))
431                 && (encoding.equals(UU) || encoding.equals(PLAIN))) {
432                 throw new BuildException("SMTP auth only possible with MIME mail");
433             }
434             // SSL only allowed with MIME mail
435
if (!autoFound && (ssl)
436                 && (encoding.equals(UU) || encoding.equals(PLAIN))) {
437                 throw new BuildException("SSL only possible with MIME mail");
438             }
439             // try UU format
440
if (encoding.equals(UU)
441                  || (encoding.equals(AUTO) && !autoFound)) {
442                 try {
443                     mailer = (Mailer) ClasspathUtils.newInstance(
444                             "org.apache.tools.ant.taskdefs.email.UUMailer",
445                             EmailTask.class.getClassLoader(), Mailer.class);
446                     autoFound = true;
447                     log("Using UU mail", Project.MSG_VERBOSE);
448                 } catch (BuildException e) {
449                     Throwable JavaDoc t = e.getCause() == null ? e : e.getCause();
450                     log("Failed to initialise UU mail: " + t.getMessage(),
451                             Project.MSG_WARN);
452                     return;
453                 }
454             }
455             // try plain format
456
if (encoding.equals(PLAIN)
457                  || (encoding.equals(AUTO) && !autoFound)) {
458                 mailer = new PlainMailer();
459                 autoFound = true;
460                 log("Using plain mail", Project.MSG_VERBOSE);
461             }
462             // a valid mailer must be present by now
463
if (mailer == null) {
464                 throw new BuildException("Failed to initialise encoding: "
465                      + encoding);
466             }
467             // a valid message is required
468
if (message == null) {
469                 message = new Message();
470                 message.setProject(getProject());
471             }
472             // an address to send from is required
473
if (from == null || from.getAddress() == null) {
474                 throw new BuildException("A from element is required");
475             }
476             // at least one address to send to/cc/bcc is required
477
if (toList.isEmpty() && ccList.isEmpty() && bccList.isEmpty()) {
478                 throw new BuildException("At least one of to, cc or bcc must "
479                      + "be supplied");
480             }
481             // set the mimetype if not done already (and required)
482
if (messageMimeType != null) {
483                 if (message.isMimeTypeSpecified()) {
484                     throw new BuildException("The mime type can only be "
485                          + "specified in one location");
486                 }
487                 message.setMimeType(messageMimeType);
488             }
489             // set the character set if not done already (and required)
490
if (charset != null) {
491                 if (message.getCharset() != null) {
492                     throw new BuildException("The charset can only be "
493                          + "specified in one location");
494                 }
495                 message.setCharset(charset);
496             }
497
498             // identify which files should be attached
499
Vector JavaDoc files = new Vector JavaDoc();
500             if (attachments != null) {
501                 Iterator JavaDoc iter = attachments.iterator();
502
503                 while (iter.hasNext()) {
504                     FileResource fr = (FileResource) iter.next();
505                     files.addElement(fr.getFile());
506                 }
507             }
508             // let the user know what's going to happen
509
log("Sending email: " + subject, Project.MSG_INFO);
510             log("From " + from, Project.MSG_VERBOSE);
511             log("ReplyTo " + replyToList, Project.MSG_VERBOSE);
512             log("To " + toList, Project.MSG_VERBOSE);
513             log("Cc " + ccList, Project.MSG_VERBOSE);
514             log("Bcc " + bccList, Project.MSG_VERBOSE);
515
516             // pass the params to the mailer
517
mailer.setHost(host);
518             mailer.setPort(port);
519             mailer.setUser(user);
520             mailer.setPassword(password);
521             mailer.setSSL(ssl);
522             mailer.setMessage(message);
523             mailer.setFrom(from);
524             mailer.setReplyToList(replyToList);
525             mailer.setToList(toList);
526             mailer.setCcList(ccList);
527             mailer.setBccList(bccList);
528             mailer.setFiles(files);
529             mailer.setSubject(subject);
530             mailer.setTask(this);
531             mailer.setIncludeFileNames(includeFileNames);
532             mailer.setHeaders(headers);
533
534             // send the email
535
mailer.send();
536
537             // let the user know what happened
538
int count = files.size();
539
540             log("Sent email with " + count + " attachment"
541                  + (count == 1 ? "" : "s"), Project.MSG_INFO);
542         } catch (BuildException e) {
543             Throwable JavaDoc t = e.getCause() == null ? e : e.getCause();
544             log("Failed to send email: " + t.getMessage(), Project.MSG_WARN);
545             if (failOnError) {
546                 throw e;
547             }
548         } catch (Exception JavaDoc e) {
549           log("Failed to send email: " + e.getMessage(), Project.MSG_WARN);
550           if (failOnError) {
551             throw new BuildException(e);
552           }
553         } finally {
554             message = savedMessage;
555         }
556     }
557
558     /**
559      * Sets the character set of mail message.
560      * Will be ignored if mimeType contains ....; Charset=... substring or
561      * encoding is not a <code>mime</code>.
562      * @param charset the character encoding to use.
563      * @since Ant 1.6
564      */

565     public void setCharset(String JavaDoc charset) {
566         this.charset = charset;
567     }
568
569     /**
570      * Returns the character set of mail message.
571      *
572      * @return Charset of mail message.
573      * @since Ant 1.6
574      */

575     public String JavaDoc getCharset() {
576         return charset;
577     }
578
579 }
580
581
Popular Tags