Embed image in email body in Jenkins pipeline Embed image in email body in Jenkins pipeline jenkins jenkins

Embed image in email body in Jenkins pipeline


You can either do this with base64 string of your image as correctly described earlier, or you can add your image as attachment in the email text and then reference this in your img src attribute.

Simple way to create html file (which will be your html body in the email) straight in the pipeline

 sh "echo '<b>Job Name: </b>${env.JOB_NAME}<br />' > mail.html" sh "echo '<b>Execution Result: </b>${currentBuild.currentResult}<br />' >> mail.html" sh "echo '<b>Build Number: </b> ${env.BUILD_NUMBER}<br />' >> mail.html" sh "echo '<b>Build URL: </b> ${env.BUILD_URL}<br />' >> mail.html"   sh "echo '<img src='cid:sample.jpg' alt='hello'>' >> mail.html"

1.) Add attachment into emailtext

   emailext attachmentsPattern: 'sample.jpg',    body: '${FILE,path="mail.html"}',   to: "${emailRecipientsList}",   recipientProviders: [[$class: 'DevelopersRecipientProvider'], [$class: 'RequesterRecipientProvider']],   subject: "Jenkins Build ${currentBuild.currentResult}: Job ${env.JOB_NAME}",   mimeType: 'text/html' 

2.) Reference the image in attachment in your img src attribude

<img src='cid:sample.jpg' alt='hello'>


You need to convert your image to Base64. I do it using python.

import base64base64Img = ''with open("image.png", "rb") as imageFile:    base64Img = base64.b64encode(imageFile.read())with open("image.html", "wb+") as writer:    writer.write('<img src="data:image/png;base64,'.encode())    writer.write(base64Img)    writer.write('">'.encode())

This writes a file ''image.html''. This file you can then append into your <body>. In my pipeline I do it like so:

${FILE,path="image.html"}


You can not add an image in .png format. Instead you can add the encoded base64 formatted image inside your html data.

To convert your actual image into base64, use LINK here.Source need to be changed.

body:"""<html><img src="data:image/png;base64<BASE64_ENCODED_IMAGE>" ></html>"""

In above code 'BASE64_ENCODED_IMAGE' is base64 convered code obtained from above link.

Please see the link for Embed Base64-Encoded Images Inline In HTML