Is it possible to send emails from the Jenkins Script Console?

Яois picture Яois · May 12, 2016 · Viewed 8.8k times · Source

To automate user registration in a new Jenkins instance, I have generated a Groovy script:

// Automatically generated groovy script -- 1463047124
jenkins.model.Jenkins.instance.securityRealm.createAccount("username", "NGRkOGJiNGE2NDEyMTExMDI0OGZmOWNj")
def user = hudson.model.User.get("username");
def userEmail = "[email protected]";
user.addProperty(new hudson.tasks.Mailer.UserProperty(userEmail)); 

Then I can either paste this into the Jenkins Script Console or run it through the Jenkins CLI, and it will create the users.

The next thing I would like to add to this setup is the ability to notify the new users their account has been created via email. I suspect this can be done, as the "mailer" is installed in my Jenkins instance. For instance, using the trendy Pipeline-as-code, I can add to my Jenkinsfile:

mail (to: "[email protected]",
        subject: "Jenkins says",
        body: "No"); 

And it will send it. However, this cannot be reproduced in the CLI, or in the Script Console. Is it even possible to do this?

Answer

luka5z picture luka5z · May 12, 2016

You could try utilize Java-like code withing your Groovy script:

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)