I need to add email notification in jenkins for both freestyle and pipeline job if the build is failed

2 Answers

0
hhami On

Post Build Actions > Email Notification

Part of the Mailer plugin.

1
xxxvodnikxxx On

reg. Email-ext plugin

enter image description here

In pipeline job you can use post build actions / try catch with proper step - ref. to mail

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 {
            echo 'This will run only if failed'
        }
        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'
        }
    }
}

or try-catch (scripted way)

try{
//code to handle
  } catch (e) {   
          emailext (
            from: '[email protected]',
            to: '[email protected]',
            subject: "job failed- ${env.JOB_NAME}, Build #${env.BUILD_NUMBER}, FAILED",
            attachLog: true,
body: """
Foooooo text 

For current build refer to: ${env.BUILD_URL}
job: ${env.JOB_NAME}
build number: #${env.BUILD_NUMBER}

With ERROR:
${e.message}
For full log refer to 
${env.BUILD_URL}
"""
          )
        throw e
   }