Skip to content

Instantly share code, notes, and snippets.

@teeks99
Created June 29, 2018 15:02
Show Gist options
  • Save teeks99/d7c331b3f66a9fe6507cfdaaabbd9229 to your computer and use it in GitHub Desktop.
Save teeks99/d7c331b3f66a9fe6507cfdaaabbd9229 to your computer and use it in GitHub Desktop.
Jenkinsfile with e-mail
pipeline {
agent any
stages {
stage('Build'){
steps {
echo "Running job: ${env.JOB_NAME}\nbuild: ${env.BUILD_ID} - ${env.BUILD_URL}\nblue ocean: ${env.RUN_DISPLAY_URL}"
}
}
}
post {
failure {
mail to: 'notify-list@example.com', from: 'jenkins@example.com',
subject: "Example Build: ${env.JOB_NAME} - Failed",
body: "Job Failed - \"${env.JOB_NAME}\" build: ${env.BUILD_NUMBER}\n\nView the log at:\n ${env.BUILD_URL}\n\nBlue Ocean:\n${env.RUN_DISPLAY_URL}"
}
}
}
@teeks99
Copy link
Author

teeks99 commented Jun 29, 2018

I was having problems getting this working with Jenkins when working with a declarative pipeline. The documentation for the mail command has all the basic parameters, but I was really wishing for a working example that glued them together.

Important Notes

Double Quotes

To get variables working in the output, use double quotes " and not single quotes '. Single quotes are just treated as Java strings by the Groovy interpreter. Double quotes are Groovy GStrings....which get parsed for variable substitution.

subject: 'Example Build: ${env.JOB_NAME} - Failed'

results in

Example Build: ${env.JOB_NAME} - Failed

while

subject: "Example Build: ${env.JOB_NAME} - Failed", 

results in

Example Build: MyTestJob - Failed

Multi Line

This also works for multi-line strings. Use """ instead of ''' to get substitution. However, I opted to use \n for line breaks instead (for the body), since putting a multi-line string in the middle of the mail command's indentation gives a bunch of indentation in the resulting e-mail body.

Multiple addresses

You can have multiple recipients of the message by having comma separated addresses in the to: field.

mail to: 'notify-list@example.com, server-operations@example.com'

Other option

I also played around with the Email Extension Plugin, but I found I didn't really need any of the added functionality offered there.

@a-pikachu
Copy link

This is life saver especially dealing with env variables.

@InbarRose
Copy link

thank you, this is very well explained and presented. exactly what I needed.
Note: You can also add "${currentBuild.fullDisplayName}" and "${currentBuild.currentResult}" for niceness.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment