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

如何在DSL任务创建Pipeline任务成功或失败后发送邮件

pipelineJob类型不支持freestyle任务专属的publishers配置段,对应不同的发信需求可以采用以下两种方案:

解决方案

场景1:需要在Job DSL脚本执行完成、成功创建Pipeline任务后发邮件

Job DSL本身运行在Jenkins的Groovy运行环境中,可以直接调用Extended Email插件的API发送邮件,直接把发信逻辑写在pipelineJob定义的外部即可,示例代码:

// 定义你的Job参数
def JobName = "test-pipeline"

pipelineJob(JobName) {
     definition {
           cps {
             script('''\
            pipeline {
                agent any
                stages {
                    stage('deploy') {
                        steps {
                          echo "Test"
                        }
                     }
                  } 
            }'''.stripIndent())
            sandbox()
          }
      }
}

// 任务创建完成后执行发信逻辑
import jenkins.model.Jenkins
import hudson.plugins.emailext.ExtendedEmailPublisher

def sendEmail() {
    def emailext = Jenkins.instance.getDescriptorByType(ExtendedEmailPublisher.DescriptorImpl.class)
    def mailParams = [
        to: "recipient@example.com",
        subject: "Pipeline任务${JobName}创建完成",
        body: "已通过Job DSL成功创建Pipeline任务:${JobName}"
    ]
    emailext.sendMail(mailParams.to, mailParams.subject, mailParams.body, false, null, null, null, null, null, null)
}

// 调用发信
sendEmail()

场景2:需要你创建的Pipeline任务自身运行结束后发邮件

不需要在Job DSL的pipelineJob外层配置publishers,直接在pipeline定义的post块中加入emailext步骤即可,这是Pipeline类型任务触发邮件通知的标准方式,示例代码:

pipelineJob("${JobName}") {
     definition {
           cps {
             script('''\
            pipeline {
                agent any
                stages {
                    stage('deploy') {
                        steps {
                          echo "Test"
                        }
                     }
                }
                // 流水线运行完成后触发邮件
                post {
                    success {
                        emailext to: "recipient@example.com",
                                 subject: "流水线${env.JOB_NAME}运行成功",
                                 body: "流水线执行完成,构建编号:${env.BUILD_NUMBER}"
                    }
                    failure {
                        emailext to: "recipient@example.com",
                                 subject: "流水线${env.JOB_NAME}运行失败",
                                 body: "流水线执行失败,请查看构建日志,构建编号:${env.BUILD_NUMBER}"
                    }
                }
            }'''.stripIndent())
            sandbox()
          }
      }
}

注意:以上两种方案都需要提前在Jenkins中安装好Extended Email插件并完成基础发信配置。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.29 04:54:02