1

In my pipeline script, I added a few environment variables but wasn't able to access it in the email-ext plugin

env.MYVAR = 'HELLO'

emailext body: '${ENV,var="MYVAR"}', subject: 'subject', to: 'hello@world.com'

Since I am reading the email body from a file, I've also tried replacing string but got java.lang.NullPointerException at org.codehaus.groovy.runtime.StringGroovyMethods.replaceAll

def myvariable = 'HELLO WORLD'
def content = readFile 'template.html'
content = content.replaceAll('MYVAR',myvariable)
...

Any idea? Thanks!

Vadim Kotov
  • 8,084
  • 8
  • 48
  • 62
qmo
  • 3,128
  • 3
  • 17
  • 23

3 Answers3

0

Try with double quotes, eg:

emailext body: "${env.MYVAR}", subject: 'subject', to: 'hello@world.com'
ianmiell
  • 151
  • 1
  • 4
0

After some hours trying i did it using string concatenation:

  pipeline {
    agent any
    stages {
       ....
  }
  post {
    always {
      script {
        env.LAST_COMMIT = sh (
            script: 'git log -n 3',
            returnStdout:true
        ).trim()
      }
      echo "Last 3 commits: $LAST_COMMIT"
      emailext (
          attachLog: true,
          body: '''$PROJECT_NAME - Build # $BUILD_NUMBER - $BUILD_STATUS:
                   Build Url: $BUILD_URL
                   Last 3 commits: '''
                   + env.LAST_COMMIT,
          postsendScript: '$DEFAULT_POSTSEND_SCRIPT',
          presendScript: '$DEFAULT_PRESEND_SCRIPT', 
          replyTo: '$DEFAULT_REPLYTO', 
          subject: '*$BRANCH_NAME - $BUILD_STATUS* - $DEFAULT_SUBJECT', 
          to: '''
            name@domain.com, name@domain.com
            ''',
          from: 'jenkins@domain.com'
      )
    }
  }
}
-1

You can specify a separate Groovy script file for the email body as follows:

emailext body: '${SCRIPT, template="build-result.groovy"}', subject 'subject', to: 'hello@world.com'

The template file needs to live in the email-templates folder of your Jenkins installation.

Then you can use the following in your Groovy script to access environment variables set in your pipeline:

<% 
def envOverrides = it.getAction("org.jenkinsci.plugins.workflow.cps.EnvActionImpl").getOverriddenEnvironment()
if (envOverrides.containsKey("MYVAR"))
{
    println "myvar = " + envOverrides["MYVAR"]
}
%>
Bill Brooks
  • 751
  • 1
  • 10
  • 30