Getting email-ext script templates to work with Jenkins pipeline

Apparently everybody know it. There are 2 way to define a pipeline: declarative pipeline (start with 'pipeline') and scripted pipeline (start with 'node')

Using declarative pipeline, it must be specified the script to execute a procedure, i.e. use def to define variables. So in pipeline case:

stage('Email') {
    steps {
        script {
            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']]
        }
    }
}

I spent some time for this, I hope it is helpfull for someone else.


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.