Jenkins Mailer插件:如何向启动构建任务的用户发送邮件
Jenkins Pipeline构建失败时发送邮件给任务启动用户的解决思路
问题核心
静态指定收件人邮箱可正常发送,但无法通过BUILD_USER_EMAIL获取启动任务用户的邮箱,需从变量注入、上下文解析两个方向解决。
解决方法1:安装插件直接获取环境变量
- 安装Build User Vars Plugin插件,重启Jenkins使其生效。
- 该插件会自动向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
相关产品推荐
相关产品推荐

