How to Jenkins pipeline to setup email notifications

Here’s an example of a Jenkins pipeline to set up email notifications for job status updates:

pipeline {
    agent any
    stages {
        stage('Build') {
            steps {
                // Add build steps here
            }
        }
    }
    post {
        always {
            // Send email notification on job completion
            mail to: 'your-email@example.com',
                 subject: "Jenkins job '${env.JOB_NAME}' (${env.BUILD_NUMBER})",
                 body: "Job status: ${currentBuild.currentResult}"
        }
    }
}

This pipeline is a basic example that sends an email notification to the specified email address when the job completes, regardless of the status (success, failure, aborted, etc.). Here are the steps to set up email notifications in Jenkins:

  1. Install and configure the “Email Extension” plugin in Jenkins.
  2. Navigate to the “Global Tool Configuration” page and add your SMTP server settings.
  3. Add the following code to your Jenkins pipeline script:
post {
    always {
        // Send email notification on job completion
        mail to: 'your-email@example.com',
             subject: "Jenkins job '${env.JOB_NAME}' (${env.BUILD_NUMBER})",
             body: "Job status: ${currentBuild.currentResult}"
    }
}
  1. Replace “your-email@example.com” with the email address you want to send notifications to.
  2. Customize the email subject and body to your liking.
  3. Save and run the pipeline to test the email notification.

You can also customize the email notification further by adding more options to the “mail” command, such as CC and BCC recipients, email attachments, and HTML content. The “Email Extension” plugin provides a comprehensive list of available options and configurations.

Leave a Reply

Your email address will not be published. Required fields are marked *