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

if(manager.build.workspace.isRemote())
{
    channel = manager.build.workspace.channel;
}

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

// list files under build workspace path
fp.list().each
{
    // 'it' is iteration value of list()
    if(it.name.endsWith('.email')) 
    {
        fpf = new hudson.FilePath(channel, manager.build.workspace.toString() + '/' + 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();
    mprops.setProperty("mail.transport.protocol","smtp");
    mprops.setProperty("mail.host",host);
    mprops.setProperty("mail.smtp.port",port);
 
    Session lSession = Session.getDefaultInstance(mprops,null);
    MimeMessage msg = new MimeMessage(lSession);
 
    StringTokenizer tok = new StringTokenizer(toAddress,";");
    ArrayList emailTos = new ArrayList();
    while(tok.hasMoreElements())
    {
        emailTos.add(new InternetAddress(tok.nextElement().toString()));
    }
    InternetAddress[] to = new InternetAddress[emailTos.size()];
    to = (InternetAddress[]) emailTos.toArray(to);
    msg.setRecipients(MimeMessage.RecipientType.TO,to);
    msg.setFrom(new InternetAddress(fromAddress));
    msg.setSubject(subject);
    msg.setText(message)
 
    Transport transporter = lSession.getTransport("smtp");
    transporter.connect();
    transporter.send(msg);
}