0
0
JenkinsHow-ToBeginner · 3 min read

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 mail step 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:

ParameterDescriptionExample
toRecipient email address'user@example.com'
subjectEmail subject line'Build Success'
bodyEmail message content'The build finished successfully.'
ccCarbon copy recipients'manager@example.com'
bccBlind 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.