How to Send Email from Jenkins Pipeline Easily
In Jenkins pipeline, you can send email using the
mail step by specifying parameters like to, subject, and body. This step sends an email notification during or after your pipeline runs.Syntax
The mail step in Jenkins pipeline sends an email. You provide the recipient with to, the email subject, and the body of the message. Optionally, you can add cc or bcc for carbon copy or blind carbon copy.
groovy
mail to: 'recipient@example.com', subject: 'Build Notification', body: 'The build has completed successfully.'
Example
This example shows a simple Jenkins pipeline that sends an email after a successful build. It uses the mail step inside the post section to notify the recipient.
groovy
pipeline {
agent any
stages {
stage('Build') {
steps {
echo 'Building...'
}
}
}
post {
success {
mail to: 'user@example.com',
subject: "SUCCESS: Job '${env.JOB_NAME} [${env.BUILD_NUMBER}]'",
body: "Good news! The build ${env.BUILD_NUMBER} succeeded."
}
}
}Output
An email is sent to user@example.com with the subject 'SUCCESS: Job 'JobName [BuildNumber]' and the body 'Good news! The build BuildNumber succeeded.'
Common Pitfalls
- Not configuring SMTP server in Jenkins global settings causes email sending to fail.
- Using incorrect email addresses or missing quotes around strings can cause syntax errors.
- Trying to send email outside of pipeline context or without the
mailstep will not work. - For multiline email bodies, use triple quotes or concatenate strings properly.
groovy
/* Wrong: Missing quotes around email */ mail to: user@example.com, subject: 'Test', body: 'Hello' /* Right: Quotes around email */ mail to: 'user@example.com', subject: 'Test', body: 'Hello'
Quick Reference
Here is a quick cheat-sheet for the mail step parameters:
| Parameter | Description | Example |
|---|---|---|
| to | Recipient email address | 'user@example.com' |
| subject | Email subject line | 'Build Success' |
| body | Email message content | 'The build finished successfully.' |
| cc | Carbon copy recipients | 'manager@example.com' |
| bcc | Blind carbon copy recipients | 'admin@example.com' |
Key Takeaways
Configure SMTP server in Jenkins global settings before sending emails.
Use the mail step with to, subject, and body parameters inside your pipeline.
Always put email addresses and strings in quotes to avoid syntax errors.
Place the mail step in the post section to send emails after build completion.
Test email sending with simple messages before adding complex content.