❝上一篇文章,我们提到了持续集成失败要立即修复。“反馈”是DevOps三要素之一的,那么流水线失败的通知邮件就算是其中一种反馈动作。 本文帮助jenkins新手,利用
Email Extension插件
,配置jenkisn邮件反馈,让团队快速收到构建情况。文章末尾有惊喜!
可能会发现有两个E-mail Notification,一个是Extended E-mail Notification另一个是E-mail Notification。前者是安装Jenkins时顺便安装的插件,后者是自带的。自带的E-mail Notification功能较弱。
本文主要介绍Email Extension
, 它允许您配置电子邮件通知的各个方面。您可以自定义电子邮件的发送时间、接收者以及电子邮件的内容。
需要在Jenkins Location中配置系统管理员邮件地址,否则会出现下面测试发送邮件会出现553 Mail from must equal authorized user
进入系统管理->系统设置->Extended E-email Notification,进行如下配置并测试是否发送成功。
该插件打包了两个 Jelly 脚本,您也可以编写自己的脚本。有两个开箱即用的默认 Jelly 脚本:一种是为 HTML 电子邮件设计的,另一种是为文本电子邮件设计的。
也可以自定义Jelly 脚本,将脚本放置在 ${JENKINS_HOME}/email-templates/
,详见 https://github.com/jenkinsci/email-ext-plugin
Text-only Jelly script
${JELLY_SCRIPT,template="text"}
HTML Jelly script
${JELLY_SCRIPT,template="html"}
stage('Email') {
steps {
script {
def mailRecipients = 'XXX@xxxxx.xxx-domain'
def jobName = currentBuild.fullDisplayName
emailext body: '''${SCRIPT, template="groovy-html.template"}''',
mimeType: 'text/html',
subject: "[Jenkins] ${jobName}",
to: "${mailRecipients}",
replyTo: "${mailRecipients}",
recipientProviders: [[$class: 'CulpritsRecipientProvider']]
}
}
}
....
post {
always
{
echo 'Send build result to members'
emailext (
mimeType: 'text/html',
attachLog: true,
compressLog: true,
subject: '$DEFAULT_SUBJECT',
body: '$DEFAULT_CONTENT',
to: 'xxx@xxxx.com.cn'
)
}
}
也可以通过共享库中封装一个email.groovy,新建文件src/org/devops/email.groovy, 在pipeline中通过Load方法调用。
//email.groovy
def Email(status,emailUser)
{
emailext body: """<!DOCTYPE html>
<html>
<head><metacharset="UTF-8"></head>
<bodyleftmargin="8 "marginwidth="0" topmargin="8"marginheight="4"offset="0">
<imgsrc="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>项目地址:<ahref="${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
}
return this
//.....
// jenkinsfile
script {
def exampleModule = load 'src/org/devops/email.groovy'
exampleModule.sendEmail("${currentBuild.result}", "${MAILRECIPIENTS}")
}
最后放上完整实例,这是一个空壳的jenkins pipeline模板,标准流程设计好了,只需要加入业务逻辑就可以了。
https://gitee.com/devops-samples/pipeline-template