Jenkins流水线执行完成后发送邮件通知
- 2020 年 3 月 15 日
- 笔记
安装插件
Jenkins需要配置邮件通知,安装插件Email Extension
,然后进入系统管理-> 系统设置
->Extended E-email Notification
。这里我使用的是QQ邮箱,填写SMTP服务器地址smtp.qq.com
和端口 465
注意要开启SSL,密码为授权码。

配置插件

邮件通知的功能很重要,我们要为每条流水线都加上这个步骤,我们在共享库中封装一个toemail.groovy
。新建文件src/org/devops/toemail.groovy
。在这个文件中,我们写了一段HTML代码,主要展示Jenkins的构建信息。
package org.devops //定义邮件内容 def Email(status,emailUser){ emailext body: """ <!DOCTYPE html> <html> <head> <meta charset="UTF-8"> </head> <body leftmargin="8" marginwidth="0" topmargin="8" marginheight="4" offset="0"> <img src="http://192.168.1.200:8080/static/0eef74bf/images/headshot.png"> <table width="95%" cellpadding="0" cellspacing="0" style="font-size: 11pt; font-family: Tahoma, Arial, Helvetica, sans-serif"> <tr> <td><br /> <b><font color="#0B610B">构建信息</font></b> </td> </tr> <tr> <td> <ul> <li>项目名称:${JOB_NAME}</li> <li>构建编号:${BUILD_ID}</li> <li>构建状态: ${status} </li> <li>项目地址:<a href="${BUILD_URL}">${BUILD_URL}</a></li> <li>构建日志:<a href="${BUILD_URL}console">${BUILD_URL}console</a></li> </ul> </td> </tr> <tr> </table> </body> </html> """, subject: "Jenkins-${JOB_NAME}项目构建信息 ", to: emailUser }
测试邮件
#!groovy @Library('jenkinslibrary@master') _ //func from shareibrary def gitlab = new org.devops.gitlab() def toemail = new org.devops.toemail() //branch branchName = branch - "refs/heads/" currentBuild.description = "Trigger by ${userName} ${branch}" gitlab.ChangeCommitStatus(projectId,commitSha,"running") //pipeline pipeline{ agent { node { label "build"}} stages{ stage("CheckOut"){ steps{ script{ println("${branchName}") } } } } post { always{ script{ println("always") } } success{ script{ println("success") gitlab.ChangeCommitStatus(projectId,commitSha,"success") toemail.Email("流水线成功",userEmail) } } failure{ script{ println("failure") gitlab.ChangeCommitStatus(projectId,commitSha,"failed") toemail.Email("流水线失败了!",userEmail) } } aborted{ script{ println("aborted") gitlab.ChangeCommitStatus(projectId,commitSha,"canceled") toemail.Email("流水线被取消了!",userEmail) } } } }
接下来可以调试了,如果没有问题会在邮箱中看到此封邮件。
