Jenkins Groovy post-build script to read workspace files and send emails with differing content

Posted on August 10th, 2016 at 20:00 PM

Jenkins Groovy post-build programming is not the best documented code base to say the least. Here's a couple of snippets gleaned from experimentation and javadocs. First the ability to read files that exist in a Jenkins job's workspace. In our case some files with a '.email' extension generated by the Jenkins job that need to be sent as email content to a recipient defined in the first line of the file. The second snippet is an emailing function independent of Jenkins plugins that sends individual emails. Grateful to Christoph Burmeister for his sendmail function here

import jenkins.*
import jenkins.model.*
import hudson.*
import hudson.model.*

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

def subject = "Send Test Email"
def toAddress = "%YOURRECIPIENT%"
def fromAddress = "%YOUREMAIL%"
def host = "%YOURMAILHOST"
def port = "25" // typical SMTP Port

    channel =;

// get build workspace path
fp = new hudson.FilePath(channel,

// list files under build workspace path
    // 'it' is iteration value of list()
        fpf = new hudson.FilePath(channel, + '/' + it.getName())
        if(fpf != null)
            lines = fpf.readToString(); //reading from file
            // eachLine can use line(value) and line(count) iteration values
            lines.eachLine{ line, count ->
                if (count == 0) 
                    // get email recipient from first line of file
                    manager.listener.logger.println('Email: ' + line)
                    toAddress = line
            sendmail(lines, subject, toAddress, fromAddress, host, port);

def sendmail(String message,String subject,String toAddress,String fromAddress,
    String host,String port)
    Properties mprops = new Properties();
    Session lSession = Session.getDefaultInstance(mprops,null);
    MimeMessage msg = new MimeMessage(lSession);
    StringTokenizer tok = new StringTokenizer(toAddress,";");
    ArrayList emailTos = new ArrayList();
        emailTos.add(new InternetAddress(tok.nextElement().toString()));
    InternetAddress[] to = new InternetAddress[emailTos.size()];
    to = (InternetAddress[]) emailTos.toArray(to);
    msg.setFrom(new InternetAddress(fromAddress));
    Transport transporter = lSession.getTransport("smtp");