Search code examples
emailjenkinsjenkins-pipelineemail-extjenkins-email-ext

Jenkins - Having issues with PostBuild Email notifications


Trying to use the following piece of code to trigger email notifications for a multi-branch pipeline job:

1    def emailNotification() {
2        def to = emailextrecipients([[$class: 'CulpritsRecipientProvider'],
3                                     [$class: 'DevelopersRecipientProvider'],
4                                     [$class: 'RequesterRecipientProvider']])
5       
6       //def to = "[email protected]"                               
7        //String currentResult = currentBuild.result
8       String currentResult = manager.build.getResult()
9       echo "CurrentResult1=${currentResult}"
10      echo "CurrentResult2=${manager.build.getResult()}"
11      echo "CurrentResult3=${manager.build.result}"
12        String previousResult = currentBuild.getPreviousBuild().result
13    
14        def causes = currentBuild.rawBuild.getCauses()
15        // E.g. 'started by user', 'triggered by scm change'
16        def cause = null
17        if (!causes.isEmpty()) {
18            cause = causes[0].getShortDescription()
19        }
20    
21        // Ensure we don't keep a list of causes, or we get
22        // "java.io.NotSerializableException: hudson.model.Cause$UserIdCause"
23        // see http://stackoverflow.com/a/37897833/509706
25        causes = null
26    
27        String subject = "${env.JOB_NAME} ${env.BUILD_NUMBER}: ${currentResult}"
28    
29        String body = """
30                      <p>Triggered by: <b>${cause}</b></p>
31    
32                      <p>Last build result: <b>${previousResult}</b></p>
33    
34    
35                      <p>Build <b>${env.BUILD_NUMBER}</b> ran on <b>${env.NODE_NAME}</b> and terminated with <b>${currentResult}</b>.
36                      </p>
37    
38                      <p>See: <a href="${env.BUILD_URL}">${env.BUILD_URL}</a></p>
39    
40                      """
41    
42        String log = currentBuild.rawBuild.getLog(40).join('\n')
43        if (currentBuild != 'SUCCESS') {
44            body = body + """
45                          <h2>Last lines of output</h2>
46                          <pre>${log}</pre>
47                          """
48        }
49    
50        if (to != null && !to.isEmpty()) {
51            // Email on any failures, and on first success.
52            if (currentResult != 'SUCCESS' || currentResult != previousResult) {
53                mail to: to, subject: subject, body: body, mimeType: "text/html"
54            }
55            echo 'Sent email notification'
56        }
57    }

Now, the problems that I'm facing:

  1. def to = emailextrecipients... is not working. I found this and this Jenkins Jira issues that this may be the causes, but no workaround. Although it seems weird that if the build is started manually, say by me a user authenticated through Github Oauth, the mail can be sent. If the Github is starting the build through the webhook, I'm getting this in the Jenkins logs:

Not sending mail to user [email protected] with no permission to view

  1. The second issue that I'm seeing is with the PostBuild email trigger. The Pipeline looks like this:

    def emailNotification() {
        //the one from above
    }
    try {
       stage('Stage1') {
           /*
           creating multiple nodes based on an array provided
           each node will execute:
           checkout scm
           buildSolution() //custom method defined
           */
           parallel <stuff_above>
       }
       stage('Stage2') {
           //do other stuff
           parallel <other_stuff_above>
        }
    } finally {
        emailNotification()
    }
    

The echoes from above (rows 9-11) are all showing null

CurrentResult1=null

CurrentResult2=null

CurrentResult3=null

Using currentBuild.currentResult will show me only SUCCESS or FAILED, but not UNSTABLE, in case some of the tests failed.

Any ideas where the problem is?


Solution

  • Build status is null until something sets it or until the job finishes. Are you using any unit test steps that would cause the build to be unstable?

    You don't need to use emailextrecipients instead use.

    emailext body: body, mimeType: 'text/html', recipientProviders: [
      [$class: 'CulpritsRecipientProvider'], 
      [$class: 'DevelopersRecipientProvider'], 
      [$class: 'RequesterRecipientProvider']], subject: subject
    

    Not sending mail to user [email protected] with no permission to view

    Means that either no jenkins user has this email address associated or the user it is associated with does not have permission to the job

    Also for causes put that logic inside a different function and add @NonCPS annotation which will stop jenkins trying to serialise state while that function is running, as you currently have it there is a small chance it will still break with that exception, see https://stackoverflow.com/a/38439681/963402