Disable email notifications using Jenkins job parameter

Posted on April 18th, 2015 at 11:00 AM


The ability to easily disable email notifications from a Jenkins job can be useful when debugging. Yes you can disable the email notifications in the job configuration but its easier at run time in the normal UI. Simply add a Boolean parameter 'SENDEMAIL' to the job and check or uncheck to enable or disable an email. Add the following code to your jobs's Editable Email Notification - Advanced Settings. Obviously replace YOUREMAILADDRESS and JOBNAME with appropriate values. If SENDEMAIL is checked then test logic takes over, in this case if a simple 'Warning' string is detected in the job console. The 'email disable' mechanism exploits the Email-ext plug predefined variable 'cancel'. When 'cancel' is true email notifications are disabled.

import hudson.model.*

// code needed for fromAddress override

import javax.mail.internet.*;
import javax.mail.*
import javax.activation.*

fromAddress = "YOUREMAILADDRESS"
InternetAddress fromAddr = new InternetAddress(fromAddress);
msg.setFrom(fromAddr);
msg.setFrom(new InternetAddress(fromAddress));

// end code for msg  fromAddress override

// get job - build - logFile to look for Warning

def job = Jenkins.getInstance().getItemByFullName("JOBNAME")
def lastbuild = job.getLastBuild()

def build = job.getBuildByNumber(lastbuild.getNumber())

def logFilePath = build.getLogFile().getPath()

String logContent = new File(logFilePath).text

// check box sets environment boolean SENDEMAIL by default
def enable = build.getEnvironment()["SENDEMAIL"]

if (logContent.contains("Warning"))
{
  logger.println("Warning - Email Notification Will Be Sent")

  if (enable.toBoolean())
  {
    logger.println("Email is Enabled")
    cancel=false
  }
  else
  {
    logger.println("Email is Disabled") 
    cancel=true
  }
}
else
{
  logger.println("Warning NOT Detected - Email Notification Will Not Be Sent")
  cancel=true
}