You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Jenkins Mailer插件:如何向启动构建任务的用户发送邮件

Jenkins Pipeline构建失败时发送邮件给任务启动用户的解决思路

问题核心

静态指定收件人邮箱可正常发送,但无法通过BUILD_USER_EMAIL获取启动任务用户的邮箱,需从变量注入、上下文解析两个方向解决。


解决方法1:安装插件直接获取环境变量

  1. 安装Build User Vars Plugin插件,重启Jenkins使其生效。
  2. 该插件会自动向Pipeline注入BUILD_USER_EMAIL环境变量,直接通过env.BUILD_USER_EMAIL引用即可:
post {
    success {
        doSomething()
    }
    failure {
        step([$class: 'Mailer', notifyEveryUnstableBuild: true, recipients: env.BUILD_USER_EMAIL, sendToIndividuals: true])
    }
    changed {
        step([$class: 'Mailer', notifyEveryUnstableBuild: true, recipients: env.BUILD_USER_EMAIL, sendToIndividuals: true])
    }
}

注意:需确保启动任务的Jenkins用户已在个人设置中填写邮箱地址。


解决方法2:通过构建上下文解析用户邮箱(无需额外插件)

若无法安装插件,可通过currentBuild对象的构建原因信息提取用户邮箱,编写自定义函数实现:

// 自定义函数:获取启动构建的用户邮箱
def getBuildInitiatorEmail() {
    def buildCauses = currentBuild.getBuildCauses()
    for (cause in buildCauses) {
        // 匹配用户触发的构建原因
        if (cause._class == 'hudson.model.Cause$UserIdCause') {
            def user = Jenkins.instance.getUser(cause.userName)
            // 获取用户的邮箱配置
            return user.getProperty(hudson.tasks.Mailer.UserProperty).address
        }
    }
    // 未找到时返回默认邮箱
    return 'fallback@example.com'
}

post {
    success {
        doSomething()
    }
    failure {
        def initiatorEmail = getBuildInitiatorEmail()
        step([$class: 'Mailer', notifyEveryUnstableBuild: true, recipients: initiatorEmail, sendToIndividuals: true])
    }
    changed {
        def initiatorEmail = getBuildInitiatorEmail()
        step([$class: 'Mailer', notifyEveryUnstableBuild: true, recipients: initiatorEmail, sendToIndividuals: true])
    }
}

注意:此方法需要Jenkins允许Pipeline脚本访问Jenkins实例对象,需在脚本安全中审批相关方法调用(如Jenkins.instance.getUser)。


内容的提问来源于stack exchange,提问作者gabolo

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.02 13:05:20