Search code examples
jenkinsgroovyjenkins-groovyemail-ext

Jenkins add/update to all jobs : should have email alerts to default recipients list


our jenkins have about 100 jobs already, i want to add editable email notification for all jobs, so that all jobs should have email alerts to default recipients list. Looking for Groovy Script for Jenkins Script Console to Add or Modify email notification Setting .

Jenkins.instance.items.each { item ->

  println("JOB: " + item.name)

  // code for setting email notification if not exist
  if(item.XXXX == null) {
    println("No email notification step ")

  } 
   else {
    //   code to update the current email settings 
    println("Set new setting")

  }
 item.save()
 println(" done")

}

Or some other automated way is also fine. Thanks !


Solution

  • Assuming you are using hudson.plugins.emailext.ExtendedEmailPublisher and all jobs already have the step added, this should probably cover the iteration part.

    // Gets all jobs and folders recursively
    items = Jenkins.instance.getAllItems();
    
    items.each { item ->
       def status = ''
       def base_email = ''
       def ext_email = []
       if (item.class.name == "hudson.model.FreeStyleProject") {
          item.publishersList.findAll {it instanceof hudson.plugins.emailext.ExtendedEmailPublisher}.each { publisher ->
             status = publisher.disabled 
             base_email=publisher.recipientList?.replaceAll("\\r|\\n", " ")
             publisher.configuredTriggers?.each { entry ->
                if (entry.email.recipientList) {
                    ext_email << "${entry.class.name.replace("hudson.plugins.emailext.plugins.trigger.", "")}: ${entry.email.recipientList?.replaceAll("\\r|\\n", " ")}"
                }
             }
          }
          if ( base_email ) {
                println item.fullName + "( " + status + " )"
                println "  +- " + base_email
                ext_email.each {             
                   println "   - " + it
                }
          } else {
             println "# " + item.fullName
          }
       }
    }
    return
    

    If you are using hudson.tasks.Mailer,it's only one field: publisher.recipients

    Then you either

    publisher.recipientList="[email protected]"
    item.save()
    

    or equivalent as needed.

    Note: Extended Email plugin has a toggle to disable sending emails "Disable Extended Email Publisher (publisher.disabled), so report on that too.

    If you need to add the plugin, then it would be something like: item.publishersList.add(new hudson.plugins.emailext.ExtendedEmailPublisher(<parameters>)(see javadoc)