groovyjenkinsemail-ext

Get build requestor using Groovy script (Jenkins / email-ext)


I want to get the username and/or email address of the build requestor in a post-build script.

Sidenote: I want the requestor so I can set the email sender of the post-build email notification dynamically in the email-ext plugin's pre-send script.

AbstractBuild has built-in support for AbstractBuild.getCulprits() and AbstractBuild.hasParticipant(User user) but I can't find a method for retrieving the requestor. I can't find any useful reference in reference list to the User class either.


Solution

  • I managed to solve it via the Cause of the the build, as recommended in this answer.

    The reason that the build requestor can be found in the cause for a build makes perfect sense when you think about it: Not every build is directly triggered by a user. If it is triggered by a user, the list of causes for the build contains a Cause.UserIdCause, with the user's id and name.

    This code snippet worked for me. It extracts the username from the build via the cause and sets the From and ReplyTo headers. I use it in the pre-send script of the email-ext Jenkins plugin.

    import javax.mail.internet.InternetAddress
    
    cause = build.getCause(hudson.model.Cause.UserIdCause.class);
    username = cause.getUserName()
    id = cause.getUserId()
    email = new InternetAddress(String.format("%s <%s@example.com>", username, id))
    
    msg.setFrom(email)
    msg.setReplyTo(email);