Getting email-ext script templates to work with Jenkins pipeline - jenkins

I recently converted to Jenkins 2.x and I am experimenting with pipeline flow, but I can't seem to get the email-ext plugin to work with groovy script templates. Although my standard flow still work fine, if I try the following I get an error with unexpected token SCRIPT
emailext mimeType: 'text/html', replyTo: 'xxxx', subject: "${env.JOB_NAME} - Build# ${env.BUILD_NUMBER} - ${env.BUILD_STATUS}", to: 'xxxx', body: "${SCRIPT, template='regressionfailed.groovy'}"
I know that there were issues with token expansion early on, but it seems like from the latest wiki updates those have been fixed. I also still get no token expansion for any tokens. Is there any good reference to get this working again. I would like to switch to the pipeline flow but the email template with token expansion is key to may work flow.

There is no problem using emailext in declarative pipeline. But your script won't be able to access "build.result" parameter correctly because it is not yet finished. Like in the default script groovy-html.template.
Edit: Actually you can access build.result if you manually set it yourself.
So it is best to add a stage in the end of the declarative pipeline like so:
stage('Send email') {
def mailRecipients = "your_recipients#company.com"
def jobName = currentBuild.fullDisplayName
emailext body: '''${SCRIPT, template="groovy-html.template"}''',
mimeType: 'text/html',
subject: "[Jenkins] ${jobName}",
to: "${mailRecipients}",
replyTo: "${mailRecipients}",
recipientProviders: [[$class: 'CulpritsRecipientProvider']]
}
Also note, that if you are using your own script you cannot name it "groovy-html.template" or " groovy-text.template" because they are default of emailext (so the file will not even be accessed). See "Script content" here.

Apparently everybody know it. There are 2 way to define a pipeline: declarative pipeline (start with 'pipeline') and scripted pipeline (start with 'node')
Using declarative pipeline, it must be specified the script to execute a procedure, i.e. use def to define variables. So in pipeline case:
stage('Email') {
steps {
script {
def mailRecipients = 'XXX#xxxxx.xxx-domain'
def jobName = currentBuild.fullDisplayName
emailext body: '''${SCRIPT, template="groovy-html.template"}''',
mimeType: 'text/html',
subject: "[Jenkins] ${jobName}",
to: "${mailRecipients}",
replyTo: "${mailRecipients}",
recipientProviders: [[$class: 'CulpritsRecipientProvider']]
}
}
}
I spent some time for this, I hope it is helpfull for someone else.

Faced the same issue today, apparently having the body defined before the emailext seem to do the trick:
def emailBody = '${SCRIPT, template="regressionfailed.groovy"}'
def emailSubject = "${env.JOB_NAME} - Build# ${env.BUILD_NUMBER} - ${env.BUILD_STATUS}"
emailext(mimeType: 'text/html', replyTo: 'xxxx', subject: emailSubject, to: 'xxxx', body: emailBody)
Remember you might still need to redo parts of your template.

I am surprised that nobody pointed out the fundamental issue with the error reported by OP. The error is coming from the Groovy compiler itself and it is coming because ${SCRIPT...} appeared inside double-quotes making it a GString (an invalid one). To fix the error mentioned in OP, you just have to use single-quotes instead:
emailext mimeType: 'text/html', replyTo: 'xxxx', subject: "${env.JOB_NAME} - Build# ${env.BUILD_NUMBER} - ${env.BUILD_STATUS}", to: 'xxxx', body: '${SCRIPT, template='regressionfailed.groovy'}'
You can reproduce the error even using the standalone Groovy interpreter like this:
$ cat << 'END' > /tmp/t.groovy
> def emailext(Map opts) {
> }
>
> emailext mimeType: 'text/html', replyTo: 'xxxx', subject: "${env.JOB_NAME} - Build# ${env.BUILD_NUMBER} - ${env.BUILD_STATUS}", to: 'xxxx', body: "${SCRIPT, template='regressionfailed.groovy'}"
> END
$ groovy /tmp/t.groovy
org.codehaus.groovy.control.MultipleCompilationErrorsException: startup failed:
/private/tmp/t.groovy: 4: unexpected token: SCRIPT # line 4, column 150.
TATUS}", to: 'xxxx', body: "${SCRIPT, te
^
1 error

Email notification for Scripted pipeline:
mail bcc: '', body: body, cc: '', from: '', replyTo: '', subject: 'Build Done', to: 'xyzh#abc.com'

Related

email on jenkins user input

I have a jenkins pipeline where I wait for user input to proceed or abort. Is there any way I can send the same in email to let the concerned person aware and he can click on the email to procceed Or abort the pipeline.?
It is possible to execute such action by using Jenkins API, this can be achieved using Jenkins Rest Api you can check this SO question.
I haven't tried this solution yet but I guess this pipeline could help you get a better idea of how I would think about implementing such behavior in a pipeline like this:
pipeline {
agent any
stages {
stage('Mail Notification') {
steps {
echo 'Sending Mail'
mail bcc: '',
body: 'Stop job through this link: ${env.BUILD_URL}/job/${env.JOB_NAME}/${env.BUILD_NUMBER}/stop',
cc: '',
from: '',
replyTo: '',
subject: 'Jenkins Job',
to: 'example#domain.com'
}
}
}
}
Jenkins pipeline is aware of such variables like ${env.BUILD_URL} ${env.JOB_NAME} ${env.BUILD_NUMBER}

Jenkins emailext plugin with default subject and body in pipeline script

I am using Jenkins with the email extension plugin and declarative pipelines. In https://jenkinsserver/configure i configured the "Default Subject" and "Default Content" which i want to use in a pipeline script.
When i add the following code to a pipeline script, everything works perfectly fine.
post {
always {
emailext (
to: 'my#my.dom',
replyTo: 'my#my.dom',
subject: "foo",
body: "bar",
mimeType: 'text/html'
);
}
}
But i don't want to specify something in the pipeline script, everything should be done whith the data specified in the global configuration. When i remove everything and just call emailext (); it failes with the comment that subject is missing. What can i do to work with default values specified globally?
As stated in the plugin documentation:
The email-ext plugin uses tokens to allow dynamic data to be inserted into recipient list, email subject line or body. A token is a string that starts with a $ (dollar sign) and is terminated by whitespace. When an email is triggered, any tokens in the subject or content fields will be replaced dynamically by the actual value that it represents.
This pipeline block should use the default subject and content from Jenkins configuration:
post {
always {
emailext (
to: 'my#my.dom',
replyTo: 'my#my.dom',
subject: '$DEFAULT_SUBJECT',
body: '$DEFAULT_CONTENT',
mimeType: 'text/html'
);
}
}
Make sure to use single quotes, otherwise Groovy will try to expand the variables.

Email-Ext plugin templates not updated

I'm working with jenkins pipeline. I'm using this plugin to send email notification with the use templates. I reused an existing templates from github.
I place the templates $Jenkins_Home\email-templates\.
But my changes are not updated in the email. Still the old content was received.
Sample code:
def call(email, subject, content, attachment = null){
def attachBuildLog = currentBuild.result != 'SUCCESS'
emailext attachLog: attachBuildLog,
body: '${SCRIPT, template="groovy-html"}',
mimeType: 'text/html',
subject: "${subject}",
to: "${email}",
replyTo: "${email}",
recipientProviders: [[$class: 'DevelopersRecipientProvider']]
}
Please advise.
Renaming the existing templates to a custom filename fixes the problem.

Jenkins Declarative Pipeline environment block variables inside email template

I need to pass some variables to an email template after build. I use environment blocks for that (some of them also are created in scripts).
Is this possible?
environment {
SUBSCRIPTION = credentials('subscription')
CERT = credentials('cert')
}
post {
always {
emailext attachLog: true,
body: '''${SCRIPT,template="email.template"}''',
compressLog: true,
mimeType: 'text/html',
subject: "SUCCESS: ${env.JOB_NAME} [${env.BUILD_NUMBER}]",
to: 'email#email.com'
}
}
I made workaround for that, in post step I trigger another job with all data that I need (pass as params) than inside scripted email template I can use them

How to send post build notification to more than one recepient in a Jenkins pipeline

I'm setting up a Jenkins pipeline wherein I want to send post build notification to more than one receipents. i'm not able to find how to set "CC", Can someone help.
An example of my pipeline is as under:
pipeline {
agent any
stages {
stage('No-op') {
steps {
sh 'ls'
}
}
}
post {
failure {
mail to: 'team#example.com',
subject: "Failed Pipeline: ${currentBuild.fullDisplayName}",
body: "Something is wrong with ${env.BUILD_URL}"
}
}
}
The above example is working fine for me, but i want to modify the following line to send notification to multiple people (preferably in CC):
mail to: 'team#example.com',
I'm using Jenkins ver. 2.41
I don't know if you can CC them, but to send to multiple recipients try using a comma-delimited list:
mail to: 'team#example.com,blah#example.com',
Use Snippet generator to explore more options regarding most of the steps. You can CC or even BCC like:
Pipeline Command :
mail bcc: 'foo#example.com', body: 'Test CC Pipeline', cc: 'xyz#example.com', from: '', replyTo: '', subject: 'Testing CC', to: 'abc#example.com'
For the emailext script, use cc within to section as below:
emailext body: 'testing',subject: 'testing', to: 'xyz#example.com,cc:abc#example.com'
reference: https://issues.jenkins-ci.org/plugins/servlet/mobile#issus/JENKINS-6703
For scripted pipeline:
mail bcc: '', body: 'Build Report', cc: '', from: '', replyTo: '', subject: 'Build Finished', to: 'example1h#xyz.com,example2#xyz.com'
I also had trouble with 'cc:' failing to send out emails. I used the 'to:' line and specified multiple users. You can do this with variables as well, if you have a list of emails you want to pull in. For example, I declared primaryOwnerEmail and secondaryOwners [list of emails] and pulled them in the 'to:' line below.
stage ("Notify Developers of Success"){
env.ForEmailPlugin = env.WORKSPACE
emailext attachmentsPattern: 'Checkmarx\\Reports\\*.pdf',
to: "${primaryOwnerEmail},${secondaryOwners}",
subject: "${env.JOB_NAME} - (${env.BUILD_NUMBER}) Finished Successfuly!",
body: "Check console output at ${env.BUILD_URL} to view the results"
}
For multiple receivers, either you can add them to to section or under cc section.
For mail pipeline syntax, see below ex :
mail to: 'user1h#domain.com, user2#domain.com', cc: 'cc1#domain.com, cc2#domain.com', bcc: '', body: 'your_body_content', from: '', replyTo: '', subject: 'your_subject_line'
For emailext pipeline syntax, append cc within to see below:
emailext to: '''user1h#domain.com, user2#domain.com, cc:cc1#domain.com, cc:cc2#domain.com''', body: 'your_body_content', from: 'sender#domain.com', subject: 'your_subject_line',

Resources