5

I started using Jenkins declarative pipelines. Now I want to have the same email notification behavior as defined in the Usage of the Mailer plugin:

  1. Every failed build triggers a new e-mail.
  2. A successful build after a failed (or unstable) build triggers a new e-mail, indicating that a crisis is over.
  3. An unstable build after a successful build triggers a new e-mail, indicating that there's a regression.
  4. Unless configured, every unstable build triggers a new e-mail, indicating that regression is still there.

I read about Notifications in Pipelines, but it does not notify based on above rules. Plus it does not contain part of the console output in the message body in case of a build failure.

Does anybody know how to do this in declarative pipeline?

Daniel Steinmann
  • 2,119
  • 2
  • 15
  • 25

1 Answers1

4

With the following code you can use the mailer plugin in the post section. This provides the expected behaviour:

pipeline {
  agent any
  stages {
      stage('test') {
        steps {
          script {
              // change to 'UNSTABLE' OR 'FAILED' to test the behaviour 
              currentBuild.result = 'SUCCESS'
          }
        }
      }
  }
  post {
        always {
          step([$class: 'Mailer',
            notifyEveryUnstableBuild: true,
            recipients: "test@test.com",
            sendToIndividuals: true])
        }
  }
}
Philip
  • 2,959
  • 1
  • 17
  • 22
  • It is important to set `currentBuild.result = 'SUCCESS'` at the beginning of the pipeline, otherwise the emails are not sent out, see [Mailer inside Pipeline](https://stackoverflow.com/questions/37169100/use-jenkins-mailer-inside-pipeline-workflow). – Daniel Steinmann May 31 '17 at 12:04
  • You're right, currentBuild.result is not automatically set in the post section of the pipeline. It might be better so set currentBuild.result = 'SUCCESS' at the very end of the job. E.g. at the beginning of the post section. See my answer in https://stackoverflow.com/questions/44329032/how-to-send-back-to-normal-notifications-in-jenkins-declarative-pipeline – Philip Jun 08 '17 at 12:38