Sunday, October 28, 2012

Send an email in Groovy using AntBuilder

Purpose: How to send an email with Groovy script.
The following example shows how can we send an email using Groovy script. You can create other type email content by setting the appropriate mime type.

In this example, we are trying to send an email notification with table of available topic from the repository.

Using groovy xml markup builder, you can most of the html tags, as shown below to create such paragraphs, hyperlinks etc..

Using AntBuilder, it allows us to attach documents as an email attachments as well.
  

//preparing an email notification
def repositoryDir = "http://prolificworks.blogspot.com"
def emailHost = mailserver_host
def fromEmail = youremail
def toEmail = receipts_email

def writer = new StringWriter()
new groovy.xml.MarkupBuilder(writer).html {
    head {
        style(type:"text/css", ''' 
        .headerRow { 
        margin: 10px; 
        padding: 1px; 
        background-color: #AAAAAA
        } 
        .lineItemRow { 
        margin: 10px; 
        padding: 1px; 
        background-color: #CCCCCC
        } 
    ''') 
    }
    body {
    h3("A Sample notification email from ProlificWorks.)
        table {
            tr('class':'headerRow') {
                th('S.No'); th('Topic Name'); th('Date')
            }
            counter = 1
            fileList.findAll {
                def temp = it
                tr('class':'lineItemRow') {
                    td("${counter}")
                    td(temp.Name)
                    td(temp.CreatedTime)
                }
                counter++
            }
       }
       a(href:"${repositoryDir}", "Repository Location:")
       p("Report Generated: ${new Date()}")
       p("For more information, you can contact us.")
    }
}

//Sending an email notification
if(fileList.size() > 0) {
    def ant = new AntBuilder()
    ant.mail(mailhost:"${emailHost}", messagemimetype:'text/html',
             subject:"A Sample notification email from ProlificWorks."){
        from(address:"${fromEmail}")
        to(address:"${toEmail}")
        message(writer)
        attachments(){
           fileset(dir:"${repoDirPath}"){
             include(name:"<>")
        }
    }
    }   
}

I hoe this post helps you, you can post comment/question for more information. Thank you for reading the post. Let us explore more Groovy together.

No comments: