how to send email from jenkins code example
Example: send email using jenkins pipeline
pipeline {
agent any
stages {
stage('PreBuild-Email') {
steps {
script {
def mailRecipients = '[email protected]'
def jobName = currentBuild.fullDisplayName
//emailext body: '''${SCRIPT, template="groovy-html.template"}''',
emailext body: '''Hello''',
mimeTye: 'text/html',
subject: "[Jenkins] Started ${jobName}",
to: "${mailRecipients}",
replyTo: "${mailRecipients}",
recipientProviders: [[$class: 'CulpritsRecipientProvider']]
}
}
}
stage('Code Checkout'){
steps {
echo 'Fetching Source Code..'
git credentialsId: 'user-creds', url: 'https://github.com/admin/shopper.git'
// sh 'pwd'
//sh 'ls'
}
}
stage('Build') {
tools {
jdk "openjdk-1.8"
}
steps {
echo 'Building Code'
sh 'java -version'
withGradle {
// some block
sh 'pwd'
sh './gradlew test:build'
}
}
}
stage('Docker Login') {
steps {
echo 'Docker Account Login'
//sh 'docker login --username=<username> --password=<password>'
}
}
stage('Docker Push') {
steps {
echo 'Pushing test docker image to Docker-Hub'
//sh 'docker push example/test'
}
}
// stage('Email') {
// steps {
// echo 'Sending Email to Engineering Team'
// emailext body: 'Successfully Build and Push Docker image', subject: 'Successfully Build and Push Docker image', to: '[email protected]'
// }
// }
}
// post {
// always {
// emailext body: 'Successfully Build and Push Docker image', subject: 'Successfully Build and Push Docker image', to: '[email protected]'
// }
// }
environment {
EMAIL_TO = '[email protected]'
}
post {
success {
emailext body: 'Check console output at $BUILD_URL to view the results. \n\n ${CHANGES} \n\n -------------------------------------------------- \n${BUILD_LOG, maxLines=100, escapeHtml=false}',
to: "${EMAIL_TO}",
subject: 'Build Success in Jenkins: $PROJECT_NAME - #$BUILD_NUMBER'
}
failure {
emailext body: 'Check console output at $BUILD_URL to view the results. \n\n ${CHANGES} \n\n -------------------------------------------------- \n${BUILD_LOG, maxLines=100, escapeHtml=false}',
to: "${EMAIL_TO}",
subject: 'Build failed in Jenkins: $PROJECT_NAME - #$BUILD_NUMBER'
}
unstable {
emailext body: 'Check console output at $BUILD_URL to view the results. \n\n ${CHANGES} \n\n -------------------------------------------------- \n${BUILD_LOG, maxLines=100, escapeHtml=false}',
to: "${EMAIL_TO}",
subject: 'Unstable build in Jenkins: $PROJECT_NAME - #$BUILD_NUMBER'
}
changed {
emailext body: 'Check console output at $BUILD_URL to view the results.',
to: "${EMAIL_TO}",
subject: 'Jenkins build is back to normal: $PROJECT_NAME - #$BUILD_NUMBER'
}
}
}