是否可以从Jenkins脚本控制台发送电子邮件?

问题描述:

要在新的Jenkins实例中自动执行用户注册,我生成了Groovy脚本:

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 = "username@domain.com";
user.addProperty(new hudson.tasks.Mailer.UserProperty(userEmail)); 

然后,我可以将其粘贴到Jenkins脚本控制台中,或者通过Jenkins CLI运行它,它将创建用户.

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

我要添加到此设置的下一件事情是,能够通过电子邮件通知新用户其帐户已创建.我怀疑可以这样做,因为在我的Jenkins实例中安装了邮件程序".例如,使用 trendy 流水线代码,我可以将其添加到我的Jenkinsfile中:

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: "user@userland.com",
        subject: "Jenkins says",
        body: "No"); 

它将发送它.但是,这不能在CLI或脚本控制台中复制.甚至有可能这样做吗?

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?

您可以尝试在Groovy脚本中使用类似Java的代码:

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.'
}

用法示例:

sendMail('mailhost', messageSender, messageReceivers, messageSubject, messageAllText)