Jenkins流水线在构建失败时没有发送电子邮件

6
我在我的Jenkins作业管道中使用以下步骤:

我在我的流水线Jenkins作业中使用以下步骤:

step([$class: 'Mailer', notifyEveryUnstableBuild: true, recipients: 'my@xyz.com', sendToIndividuals: true])

但是当构建失败时(即出现错误)没有发送任何电子邮件。有什么建议吗?

附注:可以从此服务器发送电子邮件,我已经测试过了。


检查了主要的Jenkins配置中的电子邮件设置,而不是作业中的设置。 - Torsten
2个回答

17

使用新语法的声明式流水线,例如:

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'
        }
    }
}

您可以在官方的Jenkins网站中找到更多信息:

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

请注意,这种新的语法可以使您的流水线更易于阅读、逻辑性更强且更易于维护。


很遗憾,我正在使用较旧的 Jenkins 版本(1.6.X)。 - Saikat
请查看我的答案:https://dev59.com/mpbfa4cB1Zd3GeqPv5qX 我认为你遇到了同样的问题。 - Daniel Hernández
@DanielHernández 感谢您的回答,它为我节省了很多时间。但是有一个观察结果:mail 声明的一行是不好的变体,最好像这样切割它 https://www.cloudbees.com/blog/mail-step-jenkins-workflow - ipeacocks

0

您需要手动将构建结果设置为失败,并确保它在工作区中运行。例如:

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

该插件正在检查currentBuild.result的状态,通常情况下在脚本完成之后才会更改。


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接