Search code examples
jenkinsjenkins-pipelinejenkins-groovy

Jenkins declarative pipeline send email at every stage


Hi I am trying send email at every stage in a Jenkins pipeline . Is it possible ?. Basically every stage I would like to send email if it success or failure . Stages involve Build , package , deploy


Solution

  • Here is one way. I have used Slack for notification, you can replace it with mail notification.

    For the below example, it will send the success message for both the stages if stage run is success, but if any one stage is failed it will send failure message indicating that particular stage has failed and fail the build as well.

    Note: For better reuse of the post build in every stage, you can make use of shared library.

    pipeline {
        agent any
    
        stages {
            stage("Echo Environment Variable") {
        steps {
            sh "echo 'Hello World'"
        }
        post {
            success { 
                slackSend channel: '#notification', color: 'good', message: "${env.STAGE_NAME} is Success", teamDomain: 'testnotifgroup', tokenCredentialId: 'slack-token'
            }
            unstable { 
                slackSend channel: '#notification', color: 'warning', message: "${env.STAGE_NAME} is Unstable", teamDomain: 'testnotifgroup', tokenCredentialId: 'slack-token'
            }
            failure { 
                slackSend channel: '#notification', color: 'danger', message: "${env.STAGE_NAME} is Failed", teamDomain: 'testnotifgroup', tokenCredentialId: 'slack-token'
            }
        }
    }
    
    stage("Test Stage") {
        steps {
            echo 'Hello World'
        }
        post {
            success { 
                slackSend channel: '#notification', color: 'good', message: "${env.STAGE_NAME} is Success", teamDomain: 'testnotifgroup', tokenCredentialId: 'slack-token'
            }
            unstable { 
                slackSend channel: '#notification', color: 'warning', message: "${env.STAGE_NAME} is Unstable", teamDomain: 'testnotifgroup', tokenCredentialId: 'slack-token'
            }
            failure { 
                slackSend channel: '#notification', color: 'danger', message: "${env.STAGE_NAME} is Failed", teamDomain: 'testnotifgroup', tokenCredentialId: 'slack-token'
            }
        }
    }
        }
    }
    
    

    Here is the screenshot for the same: enter image description here