Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to send email with attachment in jenkinsfile (Groovy Script)?

I want to send email after post build action in jenkins. Hence I have write jenkinsfile as follows. But I need some groovy script for 1. Attachment for zip file 2. Before attaching the file , I need to convert the folder to zip format.

Note: Please don't suggest email plugin procedure & configuration. I preferred Jenkins file method configuration

 pipeline {
    agent any
    stages {
        stage('Testing') {
            steps {
                sh 'chmod +x mvnw'
                sh './mvnw clean verify serenity:aggregate'
            }
        }
    }
    post {
        failure {
            script {
                mail (to: '[email protected]',
                        subject: "Job '${env.JOB_NAME}' (${env.BUILD_NUMBER}) failed",
                        body: "Please visit ${env.BUILD_URL} for further information"
                );
                }
            }
         success {
             script {
                mail (to: '[email protected]',
                        subject: "Job '${env.JOB_NAME}' (${env.BUILD_NUMBER}) success.",
                        body: "Please visit ${env.BUILD_URL} for further information.",


                  );
                }
          }      
    }
}
like image 517
ARJUN Avatar asked Oct 21 '25 19:10

ARJUN


1 Answers

you need to use jekins zip utility to create zip file for the folder and then use the emailext plugin to send email with attachment see below example:

 pipeline {
    agent any
    stages {
        stage('Testing') {
            steps{
               bat "del test.zip"
               zip zipFile: 'test.zip', archive: false, dir: 'directory pattern as per your structure'
            }
        }
    }
    post {
        failure {
            emailext attachmentsPattern: 'test.zip', body: '''${SCRIPT, template="groovy-html.template"}''', 
                    subject: "${env.JOB_NAME} - Build # ${env.BUILD_NUMBER} - Failed", 
                    mimeType: 'text/html',to: "email id"
            }
         success {
               emailext attachmentsPattern: 'test.zip', body: '''${SCRIPT, template="groovy-html.template"}''', 
                    subject: "${env.JOB_NAME} - Build # ${env.BUILD_NUMBER} - Successful", 
                    mimeType: 'text/html',to: "email id"
          }      
    }
}
like image 52
Amit Nanaware Avatar answered Oct 24 '25 05:10

Amit Nanaware



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!