Building Custom Task in Gradle

There comes a time in every developers life when we have a need to write our own extension, addon or plugin when using open source software. In my case I was looking for a way to send the e-mail after the gradle build process completes.

In this article we will learn how to write a gradle task which will send an email. I am using Gradle Maven and Scala plugin to implement the same. The complete source code is hosted on github gradle-custom-task

Step 1: Create a gradle project.

Step 2: Open the build.gradle and define a task MailSender extending DefaultTask as follows:

class MailSender extends DefaultTask {}

Step 3: Define a Scala function sendMail() annotated with @TaskAction inside a MailSender class. Gradle will call the method when the task executes.

@TaskAction
def sendMail() {}

Step 4: sendMail task doesn’t do anything useful, so let’s add a mail sending behaviour to it.

def mailParams = [
 mailhost: "smtp.gmail.com",
 mailport:"465",
 subject: "Email Recieved",
 messagemimetype: "text/plain",
 user: "aggarwalarpit.89@gmail.com",
 password:"XXXX",
 enableStartTLS:"true",
 ssl:"true"
]
ant.mail (mailParams) {
 from (address:'aggarwalarpit.89@gmail.com')
 to (address:'aggarwalarpit.89@gmail.com')
}

Step 5: Open the command line, move inside the project directory and execute the command:

gradle clean sendMail
Advertisements