Getting email-ext script templates to work with Jenkins pipeline

naven87 picture naven87 · Oct 6, 2016 · Viewed 45.4k times · Source

I recently converted to Jenkins 2.x and I am experimenting with pipeline flow, but I can't seem to get the email-ext plugin to work with groovy script templates. Although my standard flow still work fine, if I try the following I get an error with unexpected token SCRIPT

    emailext mimeType: 'text/html', replyTo: 'xxxx', subject: "${env.JOB_NAME} - Build# ${env.BUILD_NUMBER} - ${env.BUILD_STATUS}", to: 'xxxx', body: "${SCRIPT, template='regressionfailed.groovy'}"

I know that there were issues with token expansion early on, but it seems like from the latest wiki updates those have been fixed. I also still get no token expansion for any tokens. Is there any good reference to get this working again. I would like to switch to the pipeline flow but the email template with token expansion is key to may work flow.

Answer

user3360767 picture user3360767 · Aug 14, 2017

There is no problem using emailext in declarative pipeline. But your script won't be able to access "build.result" parameter correctly because it is not yet finished. Like in the default script groovy-html.template.

Edit: Actually you can access build.result if you manually set it yourself.

So it is best to add a stage in the end of the declarative pipeline like so:

stage('Send email') {
    def mailRecipients = "[email protected]"
    def jobName = currentBuild.fullDisplayName

    emailext body: '''${SCRIPT, template="groovy-html.template"}''',
        mimeType: 'text/html',
        subject: "[Jenkins] ${jobName}",
        to: "${mailRecipients}",
        replyTo: "${mailRecipients}",
        recipientProviders: [[$class: 'CulpritsRecipientProvider']]
}

Also note, that if you are using your own script you cannot name it "groovy-html.template" or " groovy-text.template" because they are default of emailext (so the file will not even be accessed). See "Script content" here.