How to send email after Sonar Scan/ Quality Gate in Jenkins - jenkins

What I want to do is send email to users after each build with a link to Sonarqube server for that project/branch scan.
def sendEmailAfterSonarScan() {
soanrUrl = "http://lcoalhost:8080"
{ steps, domain, config ->
steps.emailext(to: "email#mydomain.com", body: '$PROJECT_NAME - Build # $BUILD_NUMBER - $BUILD_STATUS - $BUILD_URL ' + 'Please click the following link to view Sonar Report $sonarUrl', mimeType: 'text/html', subject: 'Sonar Report')
}
}
but the method fails in the pipeline with error $sonarUrl not recognised. What am I doing wrong ?
I don't know groovy, but suspect is it something to do with double or triple quotes ?

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/

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 - sending email depends on console output

I have an app in Java and I'd like to run the app with Jenkins.
The app could log info "[Email] example log" or throw a specific exception in some cases.
Now I'd like to use Jenkins to send e-mails after build when Jenkins see in its Console output:
log: [Email] .....
specific exception has been throw
I configured Editable Email Notification and Emailext (all email parameters like smtp etc are done) and I can add it to Post-build Action
[1]: https://i.stack.imgur.com/8psbf.png
but I never used Jenkins before and I don't know which trigger should I choose in that case and where/how to write 'if code' to do what I want.
EDIT: I should probably write some Pre-send Script?
If you would like to send email, then you can directly add it in the pipeline.
Configure System:
Go to Manage Jenkins-> Configure System. Here scroll down to the email notification section. If you are using Gmail then type smtp.gmail.com for the SMTP server. Click on Advanced and select Use SMTP authentication. Enter your Gmail username and password. Select the Use SSL option and enter the port number as 465. Click on Apply and then Save.
Create Jenkins Pipeline Job:
pipeline {
agent any
stages {
stage("Send Email")
{
steps {
emailext body: 'your body', subject: 'your sububject', to: 'abc#gmail.co,'
}
}
}
}
Above method was an example to show you how you can send email via pipeline.
Execute your App and then send Email:
pipeline {
agent any
stages {
stage("App execution")
{
steps {
// Execute your app
bat label: 'Execute your app', script:"yourapp.bat >log.txt "
}
}
stage("Send Email")
{
steps {
emailext body: 'your body', subject: 'your sububject', to: 'abc#gmail.co,'
}
}
}
}
Send email based on conditions
pipeline {
agent any
stages {
stage("App execution")
{
steps {
// Execute your app
bat label: 'Execute your app', script:"yourapp.bat >log.txt "
}
}
stage("Send Email")
{
steps {
// You can add condition based on your log file in previous step :
// Example : please change below code as per your logic
// if log contains "Email" then only send email
if(log.contains(" Email:")){
emailext body: 'your body', subject: 'your subject', to: 'abc#gmail.co,'
}
}
}
}
}

How to invoke email-ext plugin from Jenkins declarative script?

I am writing a simple Jenkins declarative script to run 'make' and send an email with the result (success/failure).
I can send a simple email using:
post {
success {
mail to:"myname#me.com", subject:"${currentBuild.fullDisplayName} - Failed!", body: "Success!"
}
failure {
mail to:"myname#me.com", subject:"${currentBuild.fullDisplayName} - Failed!", body: "Failure!"
}
}
The resulting email is rather simplistic.
How can I call the email-ext plugin from the script to send an old-style post-build email? (I guess this should use email-ext's groovy-text.template).
I would like to be able to access lists like CulpritsRecipientProvider and to include the tail of the console log.
You can use it in this way:
emailext (
subject: "STARTED: Job '${env.JOB_NAME} [${env.BUILD_NUMBER}]'",
body: """<p>STARTED: Job '${env.JOB_NAME} [${env.BUILD_NUMBER}]':</p>
<p>Check console output at &QUOT;<a href='${env.BUILD_URL}'>${env.JOB_NAME} [${env.BUILD_NUMBER}]</a>&QUOT;</p>""",
recipientProviders: [[$class: 'DevelopersRecipientProvider']]
)
For more information you can check:
Sending Notifications in Pipeline
Email Extension Plugin

How to include content of the html file to template of the jenkins email-ext?

I am using Jenkins and email-ext to send build notifications. Build produces small custom report stored as simple HTML in out directory. Right now I can easy attach this report to the email, but what I want is to have this report rendered to the email body itself. I know that I can write my own jelly template, but this requires access to the build server(to install jelly script), I want to avoid this too. So my questions are:
Can I include content of the arbitrary file(generated during build) to Content field of the Email-Ext plugin?
If I cannot, what is most easy way to send such report in Jenkins?
It looks like most easy way is to use 'Pre-send Script' of the Email-ext
Script looks like this:
def reportPath = build.getWorkspace().child("HealthTestResults.html")
msg.setContent(reportPath.readToString(), "text/html");
It renders content of the HealthTestResults.html located in the root of the workspace just as body of the message.
Easy way to include the html file to email content is to add below line in the default content = ${FILE, path="yourfilename.html"}
this works for me in jenkins email ext plugin
If you use groovy template, then you can do something like this
stage("Notifications") {
steps {
script {
env.ForEmailPlugin = env.WORKSPACE
emailext mimeType: "text/html",
body: '''${SCRIPT, template="notification.template"}''',
subject: env.JENKINS_PROJECT + " " + currentBuild.currentResult + " : " + env.JOB_NAME + "/" + env.GIT_COMMIT,
recipientProviders: [requestor(), developers()],
from: env.JENKINS_EMAIL,
attachLog: true
}
}
}
and slice of /var/lib/jenkins/email-templates/notification.template
<!-- ARGOCD SYNC OUTPUT -->
<h3>ArgoCD<h3/>
<hr size="1" />
<tt>
${new File("/tmp/sync.txt").text.replaceAll('\n','<br>').replaceAll(' ', ' ')}
</tt>

Resources