[Tips] 使用Groovy處理郵件通知
Posted on 2008-08-27 18:55 laogao 閱讀(754) 評(píng)論(0) 編輯 收藏 所屬分類: On Java 、Programming in General 、Other Languages通過(guò)Groovy實(shí)現(xiàn)郵件通知(其實(shí)是轉(zhuǎn)發(fā)到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?
?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?
這個(gè)簡(jiǎn)單的例子很好的展示了如下Groovy特性:
1- Groovy腳本可以不需要定義任何class,方法定義和實(shí)際調(diào)用也可以混在一起,十分順手。
2- 定義變量不需要指定類型,只要賦值即可,不過(guò)運(yùn)行期依然是強(qiáng)類型。
3- 方法參數(shù)可以有默認(rèn)值。
4- List和Map的構(gòu)建直接在語(yǔ)義層面提供支持,如[a:1,b:2]和[1,2]。
5- GString使得我們可以方便的在String中引用變量甚至是表達(dá)式,如"${a.b.c}"或"${new Date()}"。
6- 邏輯判斷在true/false基礎(chǔ)上有所擴(kuò)展,[](0個(gè)元素的List)和null均做false處理。
7- Closure支持,方便我們?cè)谕鈬a處“當(dāng)場(chǎng)”指定處理邏輯,省去了大多數(shù)在Java中需要匿名內(nèi)部類來(lái)處理的麻煩,如attachment.files.each { .... },只有一個(gè)傳入?yún)?shù)時(shí),可直接用it指代。
8- 與ANT的無(wú)縫集成,以及對(duì)Builder模式的良好支持,使得我們可以寫(xiě)出上述初看上去有些不可思議的代碼。
P.S. 雖然Groovy自己已經(jīng)bundle了ANT,可以直接使用其中的絕大多數(shù)功能,不過(guò)為了調(diào)用ANT的mail task,還需要將ANT發(fā)行版中帶有的ant-javamail.jar以及JavaMail API對(duì)應(yīng)的jar包(可以從Sun網(wǎng)站下載)加到classpath。如果你的JDK版本低于6.0,還需要activation.jar。