Jenkins中配置郵件通知實例演示

前言:本文經過安裝配置Jenkins實現郵件通知,告知一個C# Git Repo的build成功與否

1、預配條件

  1. 在windows上安裝Jenkins和它推薦安裝的Plugins
  2. 建立一個@163.com郵箱帳號,用來發送郵件
  3. 準備一個測試用的git repo,此處我提供了 https://github.com/wenboyang214/jenkinsCsharpTest.git
  4. 運行下列腳本,Jenkins須要設置git、msbuild等的環境變量,請自行設置

2、對郵箱帳號自己進行設置(此處以163郵箱爲例)

Note: Jenkins中配置的郵箱secret須要受權碼,而不是密碼自己。所以咱們須要獲取受權碼。html

3、配置Jenkins 的系統參數

你須要作以下截圖的配置git

1.最好更改一下Jenkins的Workspace Root Directory,避免符號的一些錯誤

2.設置Jenkins的System Admin e-mail address,此處的郵箱要和你email notification的郵箱一致

3.在Extended E-mail Notification中進行以下設置,沒設置的地方,保持默認

4、測試郵箱提醒功能

1.簡單建立一個新的Pipeline item 名稱爲」test」

2.將下列腳本copy到Pipeline script中

#!/usr/bin/env groovy Jenkinsfile
pipeline {
    agent any
    environment {
        def gitRepo="https://github.com/wenboyang214/jenkinsCsharpTest.git"
        def mailRecipients="wenbya@163.com"
    }
    stages {
        stage('1. check the git repo'){
        steps{
                git "${gitRepo}" 
            }
         }
        stage('3. msbuild the project'){
            steps{
                bat "msbuild .\\JenkinsTest\\JenkinsTest.sln"
            }
        }
    }
    post {
        always {
            echo 'testing email notification'
        }
        success {
            echo 'This will run only if successful'
            emailext( 
                body: '''${SCRIPT, template="groovy-html.template"}''',
                mimeType: 'text/html',
                subject: "[Jenkins]${currentBuild.fullDisplayName}",
                to: "${mailRecipients}",
                replyTo: "${mailRecipients}",
                recipientProviders: [[$class: 'CulpritsRecipientProvider'],[$class: 'DevelopersRecipientProvider']]
            )
        }
        failure {
            echo 'This will run only if failed'
            emailext( body: '''${SCRIPT, template="groovy-html.template"}''',
                mimeType: 'text/html',
                subject: "[Jenkins]${currentBuild.fullDisplayName}",
                to: "${mailRecipients}",
                replyTo: "${mailRecipients}",
                recipientProviders: [[$class: 'CulpritsRecipientProvider'],[$class: 'DevelopersRecipientProvider']]
            )
        }
        unstable {
            echo 'This will run only if the run was marked as unstable'
        }
        changed {
            echo 'This will run only if the state of the Pipeline has changed'
            echo 'For example, if the Pipeline was previously failing but is now successful'
        }
    }
}

而後直接啓動這個test itemgithub

5、進行對錯改動,並檢查郵箱是否收到郵件

更改msbuild的路徑,故意讓其build出錯,檢查是否能收到報錯郵件。windows

bat 「msbuild .\JenkinsTest\JenkinsTest.sln」 => bat 「msbuild .\JenkinsTest1\JenkinsTest.sln」

相關文章
相關標籤/搜索