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

时间:2016-05-12 14:32:45

标签: jenkins groovy continuous-integration jenkins-cli

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

// 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运行它,它将创建用户。

我想要添加到此设置的下一件事是能够通过电子邮件通知新用户他们的帐户已创建。我怀疑这可以做,就像#"邮件"安装在我的Jenkins实例中。例如,使用潮流 Pipeline-as-code,我可以添加到我的Jenkinsfile:

mail (to: "user@userland.com",
        subject: "Jenkins says",
        body: "No"); 

它会发送它。但是,这无法在CLI或脚本控制台中重现。甚至可以这样做吗?

2 个答案:

答案 0 :(得分:4)

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

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)

答案 1 :(得分:0)

这个剧本非常棒!!效果很好...... 但我将其修改为:

i)调用jenkins环境变量以在我的电子邮件主题中发送Build Status。

ii)根据我的要求发送多行电子邮件正文,如下所示 - 希望它有所帮助!! (除了上面提到的脚本之外,还添加了以下部分)

def result = manager.build.result
manager.listener.logger.println "And the result is: ${result}"
def environment = manager.getEnvVars()
def body = "Job Name: ${environment.JOB_NAME} "+ 
System.getProperty("line.separator")+" Build Number: 

${environment.BUILD_NUMBER} "+ System.getProperty("line.separator")+" Build 
Status: ${result} " + System.getProperty("line.separator") 
    + " DEPLOYMENT INFORMATION: Check Deployment Console Output at ${environment.BUILD_URL} "
    + System.getProperty("line.separator")
    + " Disclaimer: Please do not reply to this email as this is an auto-generated email from Jenkins"

def subject = " ${environment.JOB_NAME}>> ${environment.BUILD_NUMBER} >> ${result} "
sendMail('hostxyz@com', "jenkins@com", "abc@com", "APPID>>${subject}", "${body}")