0

In my Jenkins step I have windows batch command which runs a java jar file (java -Dfile.encoding=UTF-8 -jar C:\Test1\Test.jar C:\Test\test.log) and output of which is a String value (verified Jenkins console the string is getting printed) . How will I use this string content and insert in the editable email content body so I can send this content as an email . I wouldn't want the whole Jenkins console in the email only this String. I would assume the string has to be set as an environment variable after the script runs . Not sure how exactly I can use EnvInjPlugin for my scenario if at all it can be.

Harikrishnan R
  • 11
  • 1
  • 2
  • 10

2 Answers2

1

Try to use pre-send script.

For example You have in log the string like: "this random integer should be in email content: 3432805" and want to add randomly generated integer to email content.

  1. Set the Default Content with whatever you want but add some value which will be replaced. For example:

    This is the random int from build.log: TO_REPLACE

  2. Then click "Advanced Settings" and add Pre-send Script:

    String addThisStringToContent = "";
    build.getLog(1000).each() { line ->
          java.util.regex.Pattern p = java.util.regex.Pattern.compile("random\\sinteger.+\\:\\s(\\d+)");
          java.util.regex.Matcher m = p.matcher(line);
          if (m.find()) {
                addThisStringToContent = m.group(1);
          }
    }
    
    if (addThisStringToContent == "") {
          logger.println("Proper string not found. Email content has not been updated.");
    } else {
          String contentToSet = ((javax.mail.Multipart)msg.getContent()).getBodyPart(0).getContent().toString().replace("TO_REPLACE", addThisStringToContent);
          msg.setContent(contentToSet, "text/plain");
    }
    

where:

  • build.getLog(1000) - retrieves the last 1000 lines of build output.
  • Pattern.compile("random\\sinteger.+\\:\\s(\\d+)") - regex to find the proper string
  • "text/plain" - Content Type
  • String contentToSet = ((javax.mail.Multipart)msg.getContent()).getBodyPart(0).getContent().toString().replace("TO_REPLACE", addThisStringToContent); - replaces the string TO_REPLACE with your value

Hope it will help you.

Alex
  • 56
  • 3
1

Unfortunately I have not enough reputation to comment Alex' great answer, so I write a new answer. The call

msg.setContent(contentToSet, "text/plain")

has two disadvantages:

  • Special characters are garbled
  • An attachment gets lost

So I use the following call to set the modified text

((javax.mail.Multipart)msg.getContent()).getBodyPart(0).setContent(contentToSet, "text/plain;charset=UTF-8")

some guy
  • 166
  • 4