6

I am using following step in my pipeline jenkins job:

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

But no email was sent when the build failed (i.e. error). Any pointers why?

P.S. Emails can be sent from this server, I have tested that.

Vadim Kotov
  • 8,084
  • 8
  • 48
  • 62
Saikat
  • 14,222
  • 20
  • 104
  • 125

2 Answers2

17

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.

Daniel Hernández
  • 4,078
  • 6
  • 27
  • 38
  • Unfortunately I am using an old version (1.6.X) of Jenkins. – Saikat May 02 '17 at 04:02
  • Please, check my answer here: http://stackoverflow.com/questions/36948606/jenkins-notifying-error-occured-in-different-steps-by-sending-mail-in-pipeline I think you are having the same issue – Daniel Hernández May 02 '17 at 04:20
  • @DanielHernández thanks for answer, it saved me a lot of time. But one observation: one line `mail` declaration is bad variant, better to cut it, like this https://www.cloudbees.com/blog/mail-step-jenkins-workflow – ipeacocks Apr 25 '18 at 11:00
0

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.

Kendall Trego
  • 1,975
  • 13
  • 21