如何在Jenkinsfile(Groovy脚本)中实现构建后发送带Zip附件的邮件?
Solution to Zip Folder and Attach to Jenkins Emails via Jenkinsfile
Got it, let's get this sorted for you. You want to zip a specific folder and attach it to your build success/failure emails directly in the Jenkinsfile—no extra plugin configuration required. Here's how to modify your existing pipeline to make this work:
Modified Jenkinsfile with Zip & Attachment Logic
pipeline { agent any stages { stage('Testing') { steps { sh 'chmod +x mvnw' sh './mvnw clean verify serenity:aggregate' } } } post { failure { script { // Zip your target folder (update the path to match your actual folder) sh 'zip -r build-failure-artifacts.zip target/' // Send failure email with the zipped attachment mail ( to: 'email@gmail.com', subject: "Job '${env.JOB_NAME}' (${env.BUILD_NUMBER}) failed", body: "Please visit ${env.BUILD_URL} for further details.", attachments: [file: 'build-failure-artifacts.zip'] ) } } success { script { // Zip the Serenity report folder (adjust path to your report location) sh 'zip -r serenity-test-report.zip target/site/serenity/' // Send success email with the zipped report mail ( to: 'email@gmail.com', subject: "Job '${env.JOB_NAME}' (${env.BUILD_NUMBER}) succeeded!", body: "Please visit ${env.BUILD_URL} for further details.", attachments: [file: 'serenity-test-report.zip'] ) } } } }
Key Details to Note:
- Folder Path Adjustment: Replace the paths in the
zipcommands (liketarget/ortarget/site/serenity/) with the actual folder you want to package. For example, if you have logs in alogs/directory, usezip -r build-logs.zip logs/. - Zip Command: The
zip -rflag ensures we recursively package all files and subfolders inside the target directory—no content gets left out. - Attachments Parameter: The
attachmentsargument in themailfunction takes a list of file paths. If you need multiple attachments, just add more entries:attachments: [file: 'report.zip', file: 'logs.zip']. - Windows Agent Compatibility: If your Jenkins agent runs on Windows, replace the
shzip command with a PowerShell command:
Thepowershell "Compress-Archive -Path target/site/serenity/* -DestinationPath serenity-test-report.zip -Force"-Forceflag overwrites the zip file if it already exists from a previous build.
This approach keeps everything contained within your Jenkinsfile, no extra plugin setup needed—exactly what you asked for.
内容的提问来源于stack exchange,提问作者ARJUN
相关产品推荐
相关产品推荐

