Read Sean

Read me, read Sean.
posts - 508, comments - 655, trackbacks - 9, articles - 4

[Tips] 使用Groovy处理邮件通知

Posted on 2008-08-27 18:55 laogao 阅读(725) 评论(0)  编辑  收藏 所属分类: On JavaProgramming in GeneralOther Languages

通过Groovy实现邮件通知(其实是转发到ANT)十分容易,先上代码:

 1 ant = new AntBuilder()
 2 
 3 def mail(subject, body, attachment = [dir:".",files:[]]) {
 4     ant.mail(mailhost:"mail.com", mailport:"1025", user:"mailer", password:"123", subject:"${subject}") {
 5         from(address:"nobody@mail.com")
 6         to(address:"nobody@mail.com")
 7         message("${body}")
 8         attachments() {
 9             if (attachment.files) {
10                 fileset(dir:"${attachment.dir}") {
11                     attachment.files.each {
12                         include(name:it)
13                     }
14                 }
15             }
16         }
17     }
18 }
19 
20 attachment = [dir:"/tmp", files:["some.properties","some.sql"]]
21 mail("Test mail message at ${new Date()}""This is a test message.", attachment)
22 

这个简单的例子很好的展示了如下Groovy特性:
1- Groovy脚本可以不需要定义任何class,方法定义和实际调用也可以混在一起,十分顺手。
2- 定义变量不需要指定类型,只要赋值即可,不过运行期依然是强类型。
3- 方法参数可以有默认值。
4- List和Map的构建直接在语义层面提供支持,如[a:1,b:2]和[1,2]。
5- GString使得我们可以方便的在String中引用变量甚至是表达式,如"${a.b.c}"或"${new Date()}"。
6- 逻辑判断在true/false基础上有所扩展,[](0个元素的List)和null均做false处理。
7- Closure支持,方便我们在外围代码处“当场”指定处理逻辑,省去了大多数在Java中需要匿名内部类来处理的麻烦,如attachment.files.each { .... },只有一个传入参数时,可直接用it指代。
8- 与ANT的无缝集成,以及对Builder模式的良好支持,使得我们可以写出上述初看上去有些不可思议的代码。

P.S. 虽然Groovy自己已经bundle了ANT,可以直接使用其中的绝大多数功能,不过为了调用ANT的mail task,还需要将ANT发行版中带有的ant-javamail.jar以及JavaMail API对应的jar包(可以从Sun网站下载)加到classpath。如果你的JDK版本低于6.0,还需要activation.jar。



只有注册用户登录后才能发表评论。


网站导航: