How to debug Jenkin's `emailext` plugin? - jenkins

emailext is by far the most popular email plugin for Jenkins and Jenkinsfiles.
How do you debug it?
It is failing to send the expected email with no error messages. The documentation for emailext doesn't indicate any kind of return value, callback, or any other way to get the status or result of the function call.
What methods exist (if any), in general, for debugging something like this?
(If you're curious about my specific use-case, I'll embed my code)
emailext(
to: "[REDACTED]#[REDACTED].com",
replyTo: 'no-reply#[REDACTED].com',
subject: '$DEFAULT_SUBJECT',
body: getEmailBody()
)

You can enable the debug mode of the plugin under Manage Jenkins > Configure System > Extended E-mail Notification then checkbox as in the following screenshot:
In the console output of your build, were you call emailext , you should then see more logs.

Related

How to check the status of the sent email when using emailext plugin

I'm using the email Extension plugin for Jenkins 2.332.3 but when I get errors with the configuration of the email Extension my build still goes successful even if I get for example
AuthenticationFailedException message: 535 5.7.3 Authentication unsuccessful
Is there a way to get build failure if I have incorrect configurations of emailext?
My stage:
emailext(
attachmentsPattern: "test.txt",
subject: "Test",
body: "Example test",
replyTo: 'test#test.com'
)
When I have configurations valid I get
DEBUG SMTP: message successfully delivered to mail server
I briefly checked the source code of the plugin and this doesn't seem doable. All the errors are caught and handled gracefully. Check here. Also, the execution of the plugin doesn't even return a status code. Check here.
So AFAIU I don't see a way to know whether the email was sent.
Update
After thoroughly checking the code I observed that there is an option to execute a postscript after sending a mail. This script can be specified globally or within the pipeline. So I came up with a very hacky solution with some groovy. Basically, after sending the mail you can capture the response from the SMTP server. This response will have some details you can use to determine whether it's a success or a failure.
On success, you will see a response like the one below.(I used Gmail SMTP server here)
250 2.0.0 OK 1655253667 cc23-20020a05622a411700b00304f98ad3c1sm7772402qtb.29 - gsmtp
On Authentication failure, you should see something like the below.
535-5.7.8 Username and Password not accepted. Learn more at
535 5.7.8 https://support.google.com/mail/?p=BadCredentials q18-20020a05622a04d200b002f906fc8530sm8752555qtx.46 - gsmtp
As I mentioned earlier the pipeline simply swallows all the errors that are thrown and from the script, there is no way to access the current build context. Hence as a workaround, I wrote the response to a file and then marked the status of the Job based on this. Please refer to the following pipeline.
pipeline {
agent any
stages {
stage('MailAndFail') {
steps {
script{
echo "Starting Mailing"
def script = "String response = transport.getLastServerResponse();println \"Mail Response: \" + response;File file = new File(\"/var/jenkins_home/workspace/EMAIEXT2222/MailResponse.txt\");file.write response"
emailext(
to: "test#gmail.com",
subject: "Test",
body: "Example test",
replyTo: 'test#test.com',
postsendScript: "$script"
)
sh "cat MailResponse.txt"
def response = readFile(file: 'MailResponse.txt')
if(!response.contains("2.0.0 OK")) {
echo "BUILD FAILURE!!!!"
currentBuild.result = 'FAILURE'
}
}
}
}
}
}
Note: Make sure you change the file write path to a directory in the workspace /var/jenkins_home/workspace/EMAIEXT2222. Also, the print statements in the script will not be shown in the build console. You can see them in the Jenkins log. Also, make sure you approve the groovy script if you get an error that says the script doesn't have permission to execute. You can do this from here: http://JENKINSHOST/scriptApproval/

Send Email to person on build failure on his commits

I want to Send Email specific to a person who's changes caused build failure.
Have you looked up at email-ext plugin?
At post you can set up the trigger failure:
post {
failure {
emailext body: "$env.BODY_CONTENT",
mimeType: 'text/html',
recipientProviders: [requestor(), developers(), culprits()]
subject: '$DEFAULT_SUBJECT',
to: env.PROJECT_RECIPIENTS
}
}
Make sure to configure email-ext plugin.
recipientProviders will add destinations based on:
requestor: the person who started the build
developers: to every person who commit to the repo
culprits: to every person who commit since last non-broken build
You can remove developers and requestor, culprits is the option you're looking for. You can also remove to:

Add Parameter Value in Message of Jenkins Office 365 Connector

I use the Jenkins Office 365 Connector and it sends messages of the build status to MS Teams as expected.
Now I want to add the value of a Jenkins job parameter to the message.
My usecase: I use a single job to deploy several services. I want to know in the message which service was deployed.
Notification from Dev_Deploy
Latest status of build #43
Status
Build Success
Remarks
Started by user XXX
Service
service-abc
I've seen in the Advanced configuration that there are Macros and Fact Definitions. Unfortunately there is no documentation in the plugin docs. Perhaps this configuration could help?
There is no option to customize the message in the jenkins GUI.
But a custom message can be specified in the pipeline script:
steps {
// some instructions here
office365ConnectorSend webhookUrl: 'https://outlook.office.com/webhook/123456...',
message: 'Application has been [deployed](https://uat.green.biz)',
status: 'Success',
color: '#0000FF'
}
Hint: The status color is not automatically set. So you have to set the color depending on the status.
Official documentation
In order to get the repository data, you can follow instructions to create a checkout snippet through the Jenkins UI in the configuration.
Once you input the correct URL, browser, and so on, you may invoke the office365ConnectorSend plugin. You may adapt the card sent by passing the factDefinitions attribute an array of [name,template] objects as outlined in Jenkins Docs. You can find an example in the open-source code readme.
there are some defaulted add-ons, but this should set you on the correct path.
Here is an example of my office365ConnectorSend:
office365ConnectorSend (
webhookUrl: "${webhookURL}",
color: "${currentBuild.currentResult} == 'SUCCESS' ? '00ff00' : 'ff0000'",
factDefinitions:[
[ name: "Commit Message", template: "${commit_message}"],
[ name: "Pipeline Duration", template: "${currentBuild.durationString.minus(' and counting')}"]
]
)

Sending HTML report as an attachment to mail in jenkins

I am new to Jenkins. As of now I have added email notification plugin. So once my test is completed now I am getting an email with Build log.
If I want to send Load runner HTML analysis report to mail in the same, what is the procedure?
Can anyone help me here ?
Thanks.
It's possible and it's pretty simple.
Download EmailExt plug-in (https://wiki.jenkins.io/display/JENKINS/Email-ext+plugin)
Then you can use the Pipeline Syntax to easily create it.
However, here's an example your can see as a reference to what you need.
emailext attachmentsPattern: '**/*.html', body: 'Body here', subject: 'Subject here', to: 'mail#gmail.com, mail2#gmail.com, mail3#gmail.com'
attachmentsPattern uses Ant File Syntax (http://ant.apache.org/manual/dirtasks.html)
I don't know if this will help, but i'm using https://wiki.jenkins.io/display/JENKINS/HTML+Publisher+Plugin
to generate html report from the jenkins workspace ( pwd() )
stage('sysdig report'){
publishHTML(target: [
allowMissing : true,
alwaysLinkToLastBuild: false,
keepAll : true,
reportDir : "${workspace}/",
reportFiles : "sysdig-report.html",
reportName : "sysdig-report"
])
You should be able to send the file after.

How to get culprits or committers inside a Jenkins workflow with one or more SCMs

Is it possible to access information about committers and/or culprits of a Jenkins workflow job when checking out from one or more SCMs (either via checkout() or other SCM steps like git/svn)?
The intention is to use that information to notify committers and/or culprits about the job status, for example in a mail step.
A small example of a workflow definition:
node {
// checkout from one or more SCMs, e.g.
git url: '<URL>'
checkout([$class:...])
...
// how can we know about committers or culprits at this point?
$committers = ??
// send a mail to committers or culprits
mail to: '$committers', subject: 'JENKINS', body: '<information about the job status>'
}
How could this be adapted to get a collection of the committers after running the SCM steps?
Edit:
I am currently working with Jenkins version 1.596.2 and Workflow: Aggregator version 1.6 and it seems this is an open issue in JENKINS-24141
This is now possible using the email-ext plugin.
def to = emailextrecipients([[$class: 'CulpritsRecipientProvider'],
[$class: 'DevelopersRecipientProvider'],
[$class: 'RequesterRecipientProvider']])
if (to != null && !to.isEmpty()) {
mail to: to, subject: "JENKINS", body: "See ${env.BUILD_URL}"
}
However, if you just want to send an email on failures, you may want to use Mailer (based on the email-ext pipeline examples):
step([$class: 'Mailer',
notifyEveryUnstableBuild: true,
recipients: emailextrecipients([[$class: 'CulpritsRecipientProvider'],
[$class: 'RequesterRecipientProvider']])])
Using groovy within a pipeline script:
#NonCPS // Necessary to allow .each to work.
def changelist() {
def changes = ""
currentBuild.changeSets.each { set ->
set.each { entry ->
changes += "${entry.commitId} by ${entry.author.fullName}\n"
}
}
changes
}
similar to the answer from #szym, but without the #NonCPS required:
def authors = currentBuild.changeSets.collectMany { it.toList().collect { it.author } }.unique()
As you found, pending JENKINS-24141 this is not supported. Changes to Jenkins core are required.
You can get the xml info for a job in which you will find the name of the person who committed the change along with the commit messages.
http://<Jenkins URL>:<Port Number>/job/<Jobname>/<BuildNumber>/api/xml?
Give this a go in your browser. Search for "user".
You can dump this information in a text file to process.
It seems that this feature was implemented inside the email-ext plugin but the author forgot to document the way we are supposed to use this.
Please check https://issues.jenkins-ci.org/browse/JENKINS-34763 -- and add a comment there, asking for an example. I already did.
You can fetch committers email :
committerEmail = sh (
script: 'git --no-pager show -s --format=\'%ae\'',
returnStdout: true
).trim()
and send:
emailext body: 'text you choose', subject: 'subject you choose', recipientProviders: [[$class: 'DevelopersRecipientProvider']], to: committerEmail
taken from : https://medium.com/#dilunika/find-the-git-commit-user-jenkins-pipeline-b6790613f8b5
In the emailext plugin you can provide culprits, developers, requestor etc in the recipientProviders directly.
emailext body: '',
recipientProviders: [culprits(),
developers(),
brokenBuildSuspects(),
brokenTestsSuspects(),
requestor()],
subject: ''
Description
Culprits: Sends email to the list of users who committed a change since the last non-broken build till now. This list at least always include people who made changes in this build, but if the previous build was a failure it also includes the culprit list from there.
Developers: Sends email to all the people who caused a change in the change set.
Broken Build suspects: Sends email to the list of users suspected of causing the build to begin failing.
Broken Test suspects: Sends email to the list of users suspected of causing a unit test to begin failing. This list includes committers and requestors of the build where the test began to fail, and those for any consecutive failed builds prior to the build in which the test began to fail.
Source: Jenkins Pipeline Syntax - Snippet Generator
If you want to notify the culprits who broke the build, You do not need to any checks, Use email plugin in jenkins. This plugin gives you option to send mails to commiter between past good build and current broken build.
If you are using "Editable email notifier plugin" You get option of send mail to culprit.
If you are using email plugin then you get the option "Send separate e-mails to individuals who broke the build".

Resources