Jenkins pipeline email not sent on build failure

旧街凉风 提交于 2019-12-05 13:23:20

Use Declarative Pipelines using new syntax, for example:

pipeline {
    agent any
    stages {
        stage('Test') {
            steps {
                sh 'echo "Fail!"; exit 1'
            }
        }
    }
    post {
        always {
            echo 'This will always run'
        }
        success {
            echo 'This will run only if successful'
        }
        failure {
            mail bcc: '', body: "<b>Example</b><br>\n\<br>Project: ${env.JOB_NAME} <br>Build Number: ${env.BUILD_NUMBER} <br> URL de build: ${env.BUILD_URL}", cc: '', charset: 'UTF-8', from: '', mimeType: 'text/html', replyTo: '', subject: "ERROR CI: Project name -> ${env.JOB_NAME}", to: "foo@foomail.com";
        }
        unstable {
            echo 'This will run only if the run was marked as unstable'
        }
        changed {
            echo 'This will run only if the state of the Pipeline has changed'
            echo 'For example, if the Pipeline was previously failing but is now successful'
        }
    }
}

You can find more information in the Official Jenkins Site:

https://jenkins.io/doc/pipeline/tour/running-multiple-steps/

Note that this new syntax make your pipelines more readable, logic and maintainable.

You need to manually set the build result to failure, and also make sure it runs in a workspace. For example:

try {
    throw new Exception('fail!')
} catch (all) {
    currentBuild.result = "FAILURE"
} finally {
     node('master') {
        step([$class: 'Mailer', notifyEveryUnstableBuild: true, recipients: 'my@xyz.com', sendToIndividuals: true])
    }   
}

The plugin is checking currentBuild.result for the status, and this isn't normally changed until after the script completes.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!