是否可以从 Jenkins 脚本控制台发送电子邮件? [英] Is it possible to send emails from the Jenkins Script Console?

查看:12
本文介绍了是否可以从 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)

这篇关于是否可以从 Jenkins 脚本控制台发送电子邮件?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆