Search code examples
jenkinsgroovyjenkins-2

Send email from Jenkins job using Groovy Postbuild action


Is there a way to send an email from Jenkins job using Groovy Postbuild action? Similar to how it can be done using Jenkins pipeline plugin

 mail to: 'devops@acme.com',
     subject: "Job '${env.JOB_NAME}' (${env.BUILD_NUMBER}) is waiting for input",
     body: "Please go to ${env.BUILD_URL}."

Solution

  • Thanks to https://stackoverflow.com/a/37194996/4624905 I figured out that I can use JavaMail API directly. It helped me.

    import javax.mail.*
    import javax.mail.internet.*
    
    
    def sendMail(host, sender, receivers, subject, text) {
        Properties props = System.getProperties()
        props.put("mail.smtp.host", host)
        Session session = Session.getDefaultInstance(props, null)
    
        MimeMessage message = new MimeMessage(session)
        message.setFrom(new InternetAddress(sender))
        receivers.split(',').each {
            message.addRecipient(Message.RecipientType.TO, new InternetAddress(it))
        }
        message.setSubject(subject)
        message.setText(text)
    
        println 'Sending mail to ' + receivers + '.'
        Transport.send(message)
        println 'Mail sent.'
    }
    Usage Example:
    
    sendMail('mailhost', messageSender, messageReceivers, messageSubject, messageAllText)