Jenkins-pipeline-Email-Notification

Jenkins pipeline email notification | How to send email in 2022

Jenkins is an outstanding CICD tool, which is used by almost every organization to manage its CICD pipeline. Only setting up a ci/cd pipeline is not always enough as the user/developer also needs to get notified if something breaks. In this blog, we will understand how to set up the Jenkins pipeline email notification.

Jenkins pipeline email notification configuration

When you install Jenkins, it will come with a plugin called the Mailer plugin, which will help you to send emails via Jenkins.

Jenkins mailer pluggin

To use the Above plugging, we have to configure the SMTP in the Jenkins instance that you have installed. In this blog, I will be using Gmail to send Jenkins alerts.

Setup SMTP in Jenkins

Follow the below steps to configure SMTP in your Jenkins instance.

Goto manage Jenkins > configure systems

Jenkins SMTP configuration

Scroll down and lookup for ””E-mail Notification”

Jenkins mailer pluggin SMTP configuration

Fill in the below details in SMTP configuration and click on the Save button.

For this demo, we will be sending an email to the Gmail account. As per the official documentation, the SMTP host and port should be:

host:smtp.gmail.com
port: 465

Provide your email id and password in the SMTP authentication block and check the Use SSL button.

Check this blog if you are facing any issues while sending an email. Now let’s proceed further and create a Jenkins job to send a basic email alert.

Jenkins mailer pluggin SMTP configuration

Jenkins email notification pipeline

For this demo, we will be using the Jenkins pipeline to write the Jenkins job. You can read the below blogs to understand Jenkins pipeline syntax better.

Jenkins Workflows

Jenkins scripted pipeline

To create a pipeline job in Jenkins go to new item > click on pipeline and provide the job name and click on the OK button.

Jenkins new piepeline

Now go to the pipeline session and paste the below code.

pipeline {
    agent any
    stages {
        stage('Hello') {
            steps {
                echo "Hello world"
                    }
            }
        }
    post{
        always{
            mail to: "[email protected]",
            subject: "Test Email",
            body: "Test"
        }
    }
}

Pipeline explanation

  1. Pipeline
    • The pipeline should always start with the mandatory pipeline block.
  2. Agent
    • Agent signifies where the Jenkins build job should run. In this case, we have selected an agent as any
  3. Stages/stage
    • stages block consists of different executable stage blocks. 
    • At least one stage block is mandatory inside the stages block.
    • In this example, we have defined a single stage as “Hello”
  4. Steps
    • Steps blocks consist of the actual operation which needs to be performed inside Jenkins. In Step block, we are printing hello world in the console
  5. Post
    • The post-session of the Jenkins pipeline block is used for the additional steps performed once the job completes
    • In the above example, we have used post-action as always to send an email for all the actions.
    • Pass the to mail address and body of the email.

Click on the save button to save the pipeline. Go to the Build now button to run the pipeline.

You will get the below output on the successful run

Jenkins pipeline email notification logs

Now Goto your email address and verify if you have received the email notification. Below is the email notification for the above Jenkins job sent to the Gmail account.

Jenkins pipeline email notification

Jenkins pipeline email notification using Email Extension Plugin

Though mailer plugging is good for sending the basic alerts from Jenkins it does not provide advanced functionality like sending an attachment or sending a build log over email.

There is another advanced plugging available in Jenkins which is called the Email Extension Plugin.

Email Extension Plugin

You can install this plugin from the Jenkins plugging session. Before using this plugin make sure SMTP is configured in your Jenkins instance.

To configure the SMTP for Email extension plugging, Goto manages Jenkins > configure systems > lookout for Extended E-mail Notification. Click on advance options and fill in the details as per the below screenshot.

Email Extension Plugin SMTP configuration

Click on the Save button. Now goto Jenkins and create a new pipeline and paste the below code

pipeline {
    agent any
    stages {
        stage('Hello') {
            steps {
                echo "Hello world"
                    }
            }
        }
    post{
        always{
            emailext to: "[email protected]",
            subject: "Test Email",
            body: "Test"
        }
    }
}

Save the Jenkins pipeline and click on the build now button. You will get the below output on a successful run.

Jenkins pipeline email notification

Jenkins email notification to multiple recipients

Jenkins also provides the flexibility to send email notifications to multiple recipients. Multiple recipients can be added to the block of mail step separated by a comma(.).Below is the sample code for the same.

pipeline {
    agent any
    stages {
        stage('Hello') {
            steps {
                echo "Hello world"
                    }
            }
        }
    post{
        always{
            mail to: "[email protected], [email protected]",
            subject: "Test Email",
            body: "Test"
        }
    }
}

It’s also a good practice to use variables to make the pipeline more flexible and maintainable. For example, you can use a variable to store the recipient’s email addresses, and another variable to store the subject of the email, etc.

pipeline {
    agent any
    environment {
        recipientEmails = "[email protected], [email protected]"
    }
    stages {
        stage('Hello') {
            steps {
                echo "Hello world"
                    }
            }
        }
    post{
        always{
            mail to: "${recipientEmails}",
            subject: "Test Email",
            body: "Test"

Jenkins pipeline email console output

In most of the use cases, we want Jenkins to send us the build log once the jobs are complete. In this session, we will understand how to send the build console output over email once the Jenkins job succeeded/failed.

To send the console output as an email we have to use the Jenkins Email Extension Plugin. Jenkins email extension plugin provides a parameter called attachlog, which we need to set as true to send builds logs in email. Below is the complete Jenkins job to send console output over email.

pipeline {
    agent any
    stages {
        stage('Hello') {
            steps {
                echo "Hello world"
                    }
            }
        }
    post{
        always{
            emailext to: "[email protected]",
            subject: "Test Email",
            body: "Test",
            attachLog: true
        }
    }
}

Now go to your inbox and check the email. The above Jenkins job sent the build logs as an attachment to your email address.

The content of the build logs looks like this below

Jenkins pipeline email notification using email extension plugin

Jenkins pipeline email on failure

So far we have seen how to send a Jenkins email when the Jenkins job succeeds, but in the production environment, we do not want the email to be triggered for a successful job instead we wish to get notified when the Jenkins build fails.

There are two post options in which the user will get notified in the Jenkins jobs failed. One is using Post action as a failure. The failure post actions will trigger when the Jenkins jobs failed. The complete Jenkins jobs using failure as post-action can be written as

pipeline {
    agent any
    stages {
        stage('Hello') {
            steps {
                echo "Hello world"
                    }
            }
        }
    post{
        failure{
            emailext to: "[email protected]",
            subject: "jenkins build:${currentBuild.currentResult}: ${env.JOB_NAME}",
            body: "${currentBuild.currentResult}: Job ${env.JOB_NAME}\nMore Info can be found here: ${env.BUILD_URL}"
        }
    }
}

The other way is to use change as a post-action condition. The change as a post-action makes more sense as it will notify the user whenever Jenkins Build goes from a Passed to failed state or vice versa. The Jenkins jobs using changed as post-action can be written as

pipeline {
    agent any
    stages {
        stage('Hello') {
            steps {
                echo "Hello world"
                    }
            }
        }
    post{
        changed{
            emailext to: "[email protected]",
            subject: "jenkins build:${currentBuild.currentResult}: ${env.JOB_NAME}",
            body: "${currentBuild.currentResult}: Job ${env.JOB_NAME}\nMore Info can be found here: ${env.BUILD_URL}"
        }
    }
}

You can check this link to understand all Jenkins post actions.

Jenkins pipeline sends an email with an attachment

In most of the use cases, we want Jenkins to generate some reports and we want Jenkins to send us the report once the Jenkins jobs succeed. In this session, we will understand how to send an attachment to Jenkins jobs using the email extension plugin.

Below is the sample job to send an attachment over email

pipeline {
    agent any
    stages {
        stage('Hello') {
            steps {
                sh "echo 'Hello world,1' >> test.csv"
                    }
            }
    }
        post {
            always{
                archiveArtifacts artifacts: '*.csv', onlyIfSuccessful: true
                
                emailext to: "[email protected]",
                subject: "jenkins build:${currentBuild.currentResult}: ${env.JOB_NAME}",
                body: "${currentBuild.currentResult}: Job ${env.JOB_NAME}\nMore Info can be found here: ${env.BUILD_URL}",
                attachmentsPattern: '*.csv'
                
            cleanWs()
            }
        }
}

Pipeline explanation

  1. Pipeline
    • The mandatory pipeline block.
  2. Agent
    • Agent signifies where the Jenkins build job should run. In this example, the agent is any
  3. Stages/stage
    • In the above example, we have defined a single stage as “Hello”
  4. Steps
    • In Step block, we are waiting for “hello world,1” in the test.csv file
  5. Post
    • In the above example, we have used post-action as always to send an email for all the actions.
    • archiveArtifacts is used to archive the artifacts so that the artifacts are available in Jenkins.
    • Finally using the email extension plugin we are sending attachments over email.

Now go to your email address and verify if you have received the attachment.

Jenkins pipeline sends an email with an attachment

Jenkins email notification template

A Jenkins email notification template is an HTML file inside which we can define the layout and content of an email notification. This template can be used to add custom images and other elements to the email.

To use a custom email notification template, the user needs to follow below steps:

  • Create an HTML file and defines the layout and content of the email.
  • Save the HTML file to the $JENKINS_HOME/email-templates directory on the Jenkins server.
  • Now goto Manage Jenkins -> Configure System -> E-mail Notification section.
  • Add the path to your HTML file in the Advanced section, under Default Content and save the changes.
  • Once the email notification template is configured, Jenkins will use the template to format the email notifications.

Conclusion

I hope you have liked this detailed tutorial on how to send email notifications in Jenkins using a basic email plugin as well as using a more advanced email extension plugin.

We have started with a basic email notification Jenkins job and understand how to configure and use email extension to send emails with attachments and build logs. We have also understood how to send an email when the Jenkins job fails.

I hope you have liked this tutorial. Please do let me know if you are facing any other issues while following along.

5 thoughts on “Jenkins pipeline email notification | How to send email in 2022”

Leave a Comment

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

Scroll to Top