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
mailstep 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: ''orcc: ''can be left out. Iffromis 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
- Go to Manage Jenkins > System.
- Under Jenkins Location, set Jenkins URL (for example
https://jenkins.example.com/). If you skip this,BUILD_URLis empty or null in your emails. - Set System Admin e-mail address. This becomes the default sender.
- 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).
- Tick Test configuration by sending test e-mail, enter an address and click Test configuration. Fix any error shown before you touch the Jenkinsfile.
- 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.
| Condition | Runs when | Typical use |
|---|---|---|
| always | Every build, whatever the result | Archive logs, publish reports |
| changed | Result differs from the previous build | Notify on any status change |
| fixed | Previous build failed or was unstable, this one succeeded | Recovery email |
| regression | Previous build succeeded, this one failed, was unstable or was aborted | Alert on newly broken builds |
| aborted | Build was aborted manually or by a timeout | Notify about cancelled runs |
| failure | Build result is FAILURE | Failure email |
| success | Build result is SUCCESS | Deployment notices |
| unstable | Build result is UNSTABLE (often test failures) | Test failure email |
| unsuccessful | Result is anything other than SUCCESS | One block for all bad outcomes |
| cleanup | After all other post conditions | Delete 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
| Symptom | Likely cause | Fix |
|---|---|---|
| Build fails but no email arrives and the log shows no error | SMTP not configured, or the message went to spam | Run the test email in E-mail Notification and check the recipient's spam folder |
AuthenticationFailedException in the console | Wrong username or password, or the provider blocks basic auth | Use an app password or SMTP relay credentials |
| Could not connect to SMTP host | Wrong port, SSL/TLS mismatch or a firewall | Use 465 with SSL or 587 with TLS, and check outbound access from the controller |
No such DSL method 'emailext' | Email Extension plugin not installed | Install it from Manage Jenkins > Plugins |
BUILD_URL is null or empty in the email | Jenkins URL not set | Set Jenkins URL under Jenkins Location |
Email shows raw <b> tags | mimeType not set to HTML | Add mimeType: 'text/html' |
| Test failures do not trigger an email | Build is UNSTABLE, not FAILURE | Use 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
recipientProvidersinstead of hard-coding personal addresses in many jobs. - Notify on
regressionandfixedfor 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
- Jenkins Pipeline Complete Reference Tutorials
- Environment variables and properties defined in jenkins | Jenkins Tutorial
- Top 50 Jenkin pipeline interview questions and answers
- More Jenkins tutorials
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.
Find Trusted Cardiac Hospitals
Compare heart hospitals by city and services โ all in one place.
Explore Hospitals