MYHOSPITALNOW.COM

Find Trusted Doctors & Hospitals

Discover healthcare providers, compare hospitals, and explore treatment options worldwide.

Free Treatment Quotes • Doctor Search • Hospital Comparison

Find Healthcare Options

www.myhospitalnow.com

Jenkins Pipeline code for Sending an email on Build Failure

To get an email when a Jenkins build fails, call the mail step (Mailer plugin) or the emailext step (Email Extension plugin) inside the post { failure { ... } } block of a declarative Jenkinsfile. The examples above show the basic pattern. Below you'll find how to set up SMTP, a cleaned-up Jenkinsfile, a richer emailext version, every post condition, and corrected ways to let a pipeline continue after a step fails.




 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>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'  
         }  
     }  
 }Code language: PHP (php)

post {
 always {
   sh 'echo "This will always run"'
 }
 success {
  sh 'echo "This will run only if successful"'
 }
 failure {
  sh 'echo "This will run only if failed"'
 }
 unstable {
  sh 'echo "This will run only if the run was marked as unstable"'
 }
 changed {
  sh 'echo "This will run only if the state of the Pipeline has changed"'
  sh 'echo "For example, the Pipeline was previously failing but is now successful"'
  sh 'echo "... or the other way around :)"'
 }
}Code language: JavaScript (javascript)

To ignore a failed step in declarative pipeline you basically have two options:

Use script step and try-catch block (similar to previous proposition by R_K but in declarative style)
stage('someStage') {
    steps {
        script {
            try {
                build job: 'system-check-flow'
            } catch (err) {
                echo err.getMessage()
            }
        }
        echo currentBuild.result
    }
}
Use catchError
stage('someStage') {
    steps {
        catchError {
            build job: 'system-check-flow'
        }
        echo currentBuild.result
    }
}
In both cases the build won't be aborted upon exception in build job: 'system-check-flow'. In both cases the echo step (and any other following) will be executed.Code language: JavaScript (javascript)

How the example above works

In a declarative pipeline, the post section runs after all stages finish. Each condition block (always, success, failure and so on) runs only when the build matches that condition. In the first example, the Test stage runs exit 1. That marks the build FAILURE, so the failure block runs and the mail step sends an HTML message built from the JOB_NAME, BUILD_NUMBER and BUILD_URL environment variables.

  • The mail step comes from the Mailer plugin. It is part of the suggested plugin set on most installations, but it sends nothing until SMTP is configured.
  • The body and subject use double quotes so that Groovy fills in ${env.JOB_NAME} before sending. Inside single quotes, the variables would show up literally in the email.
  • mimeType: 'text/html' makes mail clients render the <b> and <br> tags. Without it, recipients see the raw tags.
  • Empty values such as from: '' or cc: '' can be left out. If from is empty, Jenkins uses the system admin email address.

Note: A failed test run published with junit usually marks the build UNSTABLE, not FAILURE. The failure block does not run for unstable builds. Use unsuccessful if you want an email for both.

Configure SMTP so Jenkins can send mail

  1. Go to Manage Jenkins > System.
  2. Under Jenkins Location, set Jenkins URL (for example https://jenkins.example.com/). If you skip this, BUILD_URL is empty or null in your emails.
  3. Set System Admin e-mail address. This becomes the default sender.
  4. Under E-mail Notification, enter the SMTP server. Click Advanced and turn on SMTP authentication, then enter the username and password, the port, and Use SSL (usually port 465) or Use TLS (STARTTLS, usually port 587).
  5. Tick Test configuration by sending test e-mail, enter an address and click Test configuration. Fix any error shown before you touch the Jenkinsfile.
  6. If you use emailext, also fill in the separate Extended E-mail Notification section. It has its own SMTP settings and credentials.

Note: For Gmail, Microsoft 365 and similar providers, use an app password or a dedicated relay account, not a personal password. Many providers block basic SMTP authentication for normal accounts.

A cleaner failure-notification Jenkinsfile

This version keeps the recipient in one place, uses unsuccessful so unstable builds also send an email, and sends a recovery message through fixed when a broken build turns green again.

pipeline {
    agent any

    environment {
        NOTIFY_TO = 'ci-team@example.com'
    }

    stages {
        stage('Build') {
            steps {
                sh 'echo "Building..."'
            }
        }
        stage('Test') {
            steps {
                sh 'echo "Fail!"; exit 1'
            }
        }
    }

    post {
        unsuccessful {
            mail to: env.NOTIFY_TO,
                 subject: "${currentBuild.currentResult}: ${env.JOB_NAME} #${env.BUILD_NUMBER}",
                 mimeType: 'text/html',
                 charset: 'UTF-8',
                 body: """<p><b>Build ${currentBuild.currentResult}</b></p>
<p>Project: ${env.JOB_NAME}<br>
Build number: ${env.BUILD_NUMBER}<br>
Build URL: <a href="${env.BUILD_URL}">${env.BUILD_URL}</a></p>"""
        }
        fixed {
            mail to: env.NOTIFY_TO,
                 subject: "FIXED: ${env.JOB_NAME} #${env.BUILD_NUMBER}",
                 body: "The build is passing again: ${env.BUILD_URL}"
        }
    }
}Code language: PHP (php)

currentBuild.currentResult always has a value (SUCCESS, UNSTABLE, FAILURE and so on). That makes it safer to use in messages than currentBuild.result, which stays null until something sets it. The triple-quoted string lets the HTML body span several lines and still fill in the variables.

Richer emails with emailext

The Email Extension plugin adds the emailext step. Use it when you want to attach the build log, include part of the console output, or email the developers whose commits are in the build instead of a fixed list.

post {
    failure {
        emailext(
            to: 'ci-team@example.com',
            recipientProviders: [culprits(), developers(), requestor()],
            subject: "FAILED: ${env.JOB_NAME} #${env.BUILD_NUMBER}",
            mimeType: 'text/html',
            attachLog: true,
            body: '''<p>Build <b>$PROJECT_NAME #$BUILD_NUMBER</b> finished with status <b>$BUILD_STATUS</b>.</p>
<p>Console: <a href="${BUILD_URL}console">${BUILD_URL}console</a></p>
<pre>${BUILD_LOG, maxLines=50}</pre>'''
        )
    }
}Code language: HTML, XML (xml)

The body uses single quotes on purpose. That way Groovy leaves $PROJECT_NAME, $BUILD_STATUS and ${BUILD_LOG, maxLines=50} alone, and the plugin's own token engine expands them. culprits() emails people who committed since the last successful build, developers() emails committers in this build, and requestor() emails the user who started the build manually.

Post conditions reference

Jenkins evaluates post conditions in a fixed order, no matter what order you write them in: always, changed, fixed, regression, aborted, failure, success, unstable, unsuccessful, cleanup.

ConditionRuns whenTypical use
alwaysEvery build, whatever the resultArchive logs, publish reports
changedResult differs from the previous buildNotify on any status change
fixedPrevious build failed or was unstable, this one succeededRecovery email
regressionPrevious build succeeded, this one failed, was unstable or was abortedAlert on newly broken builds
abortedBuild was aborted manually or by a timeoutNotify about cancelled runs
failureBuild result is FAILUREFailure email
successBuild result is SUCCESSDeployment notices
unstableBuild result is UNSTABLE (often test failures)Test failure email
unsuccessfulResult is anything other than SUCCESSOne block for all bad outcomes
cleanupAfter all other post conditionsDelete the workspace, release resources

Continuing after a failed step: corrected examples

The last example above says that with either option "the build won't be aborted". That is true, but the two options leave the build in different states. Plain catchError marks both the stage and the build as FAILURE, so echo currentBuild.result prints FAILURE and your failure email still goes out. A bare try/catch hides the error completely: the build stays green and currentBuild.result is usually null. Pass the result you actually want explicitly:

stage('System check') {
    steps {
        // Continue, mark only this stage red, keep the build green
        catchError(buildResult: 'SUCCESS', stageResult: 'FAILURE') {
            build job: 'system-check-flow'
        }

        // Or: continue but mark build and stage UNSTABLE
        warnError('system-check-flow failed') {
            build job: 'system-check-flow'
        }

        echo "Current result: ${currentBuild.currentResult}"
    }
}Code language: PHP (php)

For a downstream job specifically, you can skip the exception completely with propagate: false and decide what to do based on the result:

stage('System check') {
    steps {
        script {
            def downstream = build job: 'system-check-flow', propagate: false
            echo "Downstream result: ${downstream.result}"
            if (downstream.result != 'SUCCESS') {
                unstable("system-check-flow finished with ${downstream.result}")
            }
        }
    }
}Code language: PHP (php)

Note: Avoid catch (err) with no rethrow. It also catches the interruption raised when someone aborts the build or a timeout fires, so the pipeline can keep running after it should have stopped.

Troubleshooting

SymptomLikely causeFix
Build fails but no email arrives and the log shows no errorSMTP not configured, or the message went to spamRun the test email in E-mail Notification and check the recipient's spam folder
AuthenticationFailedException in the consoleWrong username or password, or the provider blocks basic authUse an app password or SMTP relay credentials
Could not connect to SMTP hostWrong port, SSL/TLS mismatch or a firewallUse 465 with SSL or 587 with TLS, and check outbound access from the controller
No such DSL method 'emailext'Email Extension plugin not installedInstall it from Manage Jenkins > Plugins
BUILD_URL is null or empty in the emailJenkins URL not setSet Jenkins URL under Jenkins Location
Email shows raw <b> tagsmimeType not set to HTMLAdd mimeType: 'text/html'
Test failures do not trigger an emailBuild is UNSTABLE, not FAILUREUse unstable or unsuccessful

Best practices

  • Keep SMTP credentials in Jenkins system configuration or the credentials store, never in the Jenkinsfile.
  • Send to a team distribution list or use recipientProviders instead of hard-coding personal addresses in many jobs.
  • Notify on regression and fixed for noisy jobs, so people get an email when the status changes, not on every red build.
  • Do not attach full logs from builds that may print secrets. Jenkins masks bound credentials, but other values can still leak.
  • Put shared notification logic in a shared library function so every pipeline formats emails the same way.

Frequently asked questions

Why is my Jenkins pipeline not sending emails on failure?

Usually SMTP is not configured in Manage Jenkins > System, or the credentials, port or SSL/TLS settings are wrong. Send a test email from the E-mail Notification section first. Also check that the build really is FAILURE and not UNSTABLE.

What is the difference between mail and emailext in Jenkins?

mail comes from the Mailer plugin and sends a simple message to fixed addresses. emailext comes from the Email Extension plugin. It can attach logs, use tokens such as ${BUILD_LOG}, and email committers or the user who started the build through recipientProviders.

How do I send an email when tests fail in Jenkins?

Test failures recorded with the junit step usually make the build UNSTABLE. Put the email step in an unstable or unsuccessful post block instead of failure.

How do I send an email from a scripted pipeline?

Scripted pipelines have no post section. Wrap the build in try { ... } catch (e) { mail ...; throw e }, or send the notification in a finally block that checks currentBuild.currentResult.

Can I get an email only when a broken build is fixed?

Yes. Put the email step in a fixed post block. It runs only when the previous build failed or was unstable and the current one succeeded.

Related tutorials

Find Trusted Cardiac Hospitals

Compare heart hospitals by city and services โ€” all in one place.

Explore Hospitals
I'm Rajesh Kumar, a DevOps, SRE, DevSecOps, Cloud, and Platform Engineering expert passionate about sharing practical knowledge, real-world experiences, and industry best practices. I have worked at Cotocus and regularly write about technology, travel, investing, health, product reviews, and digital marketing through my various platforms. I publish technical articles at DevOps School, travel stories at Holiday Landmark, stock market insights at Stocks Mantra, health and fitness guidance at My Medic Plus, product reviews at TrueReviewNow, and SEO and digital marketing strategies at Wizbrand.

Related Posts

Jenkins Tutorials: Scripted Pipeline jenkinsfile example

Pipeline: Basic Steps catchError: Catch error and set build result to failure deleteDir: Recursively delete the current directory from the workspace dir: Change current directory echo: Print…

Read More

Top 50 Jenkin pipeline interview questions and answers

1) How to fix a broken build for your project in Jenkins and how to make sure project build doesn’t break in Jenkins at all? The user…

Read More

Jenkins Pipeline Complete Reference Tutorials

What is a Jenkins Pipeline? Jenkins Pipeline (or simply “Pipeline”) is a suite of plugins which supports implementing and integrating continuous delivery pipelines into Jenkins. Jenkins Pipeline…

Read More

Jenkins Pipeline Tutotrials with example of jenkinsfile

Jenkins Pipeline Example Code Sample Rajesh Kumar I’m Rajesh Kumar, a DevOps, SRE, DevSecOps, Cloud, and Platform Engineering expert passionate about sharing practical knowledge, real-world experiences, and…

Read More

Jenkins Tutorials: Meaning of $class in scripted pipeline

In a Jenkins Pipeline, $class is a special map key that tells Jenkins which plugin or core class to create when a step or property accepts more…

Read More

Automating Jenkins Job Configuration: Job DSL, Multibranch, Job Generator, and JJB

Manually creating many Jenkins jobs is slow and error-prone. This guide compares the main automation options and shows practical jobs-as-code examples for repeatable setup.

Read More
Subscribe
Notify of
guest
0 Comments
Newest
Oldest Most Voted
0
Would love your thoughts, please comment.x
()
x