Prototyping and Testing Groovy Email Templates

One of the features people have requested for the Jenkins email-ext plugin is an easier way to test out their templates for Groovy generated email content. (See JENKINS-9594). The email-ext plugin supports Groovy's SimpleTemplateEngine for generating email body (and other areas). I haven't had the change to implement this feature yet, but found a fairly easy way to test out templates for builds based on a previous build. This can be used in the Jenkins Script Console to test the templates on jobs. The Groovy code below will get a project that you specify by name, create a copy of it and then perform the build step for the ExtendedEmailPublisher with the previous build you want to test with. It even prints out the build log output from the ExtendedEmailPublisher running. You can change anything about the ExtendedEmailPublisher before calling perform that you might need to. This is not the final solution, I still plan on implementing this feature when I get the time to look into it more.

import hudson.model.StreamBuildListener
import hudson.plugins.emailext.ExtendedEmailPublisher
import java.io.ByteArrayOutputStream
def projectName = "SomeProject"
Jenkins.instance.copy(Jenkins.instance.getItem(projectName), "$projectName-Testing"); 
def project = Jenkins.instance.getItem(projectName)
try {
  def testing = Jenkins.instance.getItem("$projectName-Testing")
  def build = project.lastBuild
  // or def build = project.lastFailedBuild
  // see http://javadoc.jenkins-ci.org/hudson/model/Job.html#getLastBuild() javadoc for the Job class
  //for other ways to get builds
  def baos = new ByteArrayOutputStream()
  def listener = new StreamBuildListener(baos)
  testing.publishersList.each() { p ->
    println(p)
    if(p instanceof ExtendedEmailPublisher) {
      // modify the properties as necessary here
      p.recipientList = 'me@me.com' // set the recipient list while testing
      // run the publisher
      p.perform((AbstractBuild<?,?>)build, null, listener)
      // print out the build log from ExtendedEmailPublisher
      println(new String( baos.toByteArray(), "UTF-8" ))
    }
  }
} finally {
  if(testing != null) {
    // cleanup the test job
    testing.delete()
  }
}

Update: Thanks to Josh Unger for a a few updates to the above to make it more robust