Skip to content

Instantly share code, notes, and snippets.

@TobiX
Created December 3, 2020 20:23
Show Gist options
  • Save TobiX/1677e9de3d524247e2a389a1deaa1bfd to your computer and use it in GitHub Desktop.
Save TobiX/1677e9de3d524247e2a389a1deaa1bfd to your computer and use it in GitHub Desktop.

Revisions

  1. TobiX created this gist Dec 3, 2020.
    32 changes: 32 additions & 0 deletions mailOnError.groovy
    Original file line number Diff line number Diff line change
    @@ -0,0 +1,32 @@
    def call(Map params = [:], Closure inner) {
    catchError {
    inner.call()
    }

    def notifyCulprits = params.getOrDefault('notifyCulprits', true)
    def extraMails = params.getOrDefault('extraMails', [])

    if (shouldSendMail(currentBuild)) {
    def providers = []
    if (notifyCulprits) {
    providers.add(culprits())
    }
    emailext subject: 'Jenkins - $PROJECT_NAME - Build #$BUILD_NUMBER - $BUILD_STATUS',
    body: '${SCRIPT, template="groovy-html.template"}', mimeType: 'text/html',
    recipientProviders: providers, to: extraMails.join(',')
    }
    }

    /**
    * Send email when either the current build is failed or the previous build has failed (so we send the
    * "the build is back to normal" mails)
    *
    * @param currentBuild The current build, as defined by the pipeline
    * @return true if a mail should be send, false otherwise
    */
    @NonCPS
    def shouldSendMail(currentBuild) {
    def previousBuild = currentBuild.previousBuild
    return currentBuild.resultIsWorseOrEqualTo("UNSTABLE") ||
    (previousBuild != null && previousBuild.resultIsWorseOrEqualTo("UNSTABLE"))
    }