I need to execute a groovy script which is created in the script runner in JSM when user click on a button
Scenario
I need to execute the below groovy script when user click on the "subscribe" button in the email subscription
import java.nio.file.Files
import java.nio.file.Paths
import com.atlassian.mail.Email
import com.atlassian.mail.server.SMTPMailServer
import com.atlassian.jira.component.ComponentAccessor
// Replace with your filter ID
def filterId = 14276
// Step 1: Fetch filter details
def filterDetails = get("/rest/api/2/filter/${filterId}")
.header('Content-Type', 'application/json')
.asObject(Map).body
// Extract the JQL query from the filter
def jqlQuery = filterDetails.jql
logger.warn "Executing JQL: ${jqlQuery}"
// Step 2: Execute the JQL query to fetch all fields
def searchResponse = post('/rest/api/2/search')
.header('Content-Type', 'application/json')
.body([
jql: jqlQuery // No 'fields' parameter means all fields are returned
])
.asObject(Map).body
def issues = searchResponse.issues
// Dynamically retrieve all field names from the first issue
def fieldNames = issues ? issues[0].fields.keySet() : []
logger.warn "Fields found: ${fieldNames}"
// Step 3: Prepare the CSV content
def csvContent = new StringBuilder()
// Add CSV headers dynamically based on the fields
csvContent.append("Issue Key,")
csvContent.append(fieldNames.join(","))
csvContent.append("\n")
// Iterate through the issues and format them as CSV
issues.each { Map issue ->
def key = issue.key
def fields = issue.fields
// Start with the issue key
def row = [key]
// Add each field's value, handling nulls and formatting where necessary
fieldNames.each { fieldName ->
def value = fields[fieldName]
row << (value?.toString()?.replaceAll(",", "") ?: "") // Remove commas to avoid CSV breaking
}
// Append the row to CSV content
csvContent.append(row.join(",")).append("\n")
}
// Step 4: Save the CSV to a file
def outputFilePath = "/tmp/jira_filter_${filterId}_issues.csv" // Dynamic file name based on filter ID
Files.write(Paths.get(outputFilePath), csvContent.toString().getBytes("UTF-8"))
// Log success message
logger.warn "CSV file created at: ${outputFilePath}"
// Step 5 (Optional): Send the CSV via email
def mailServer = ComponentAccessor.getMailServerManager().defaultSMTPMailServer
if (!mailServer) {
throw new IllegalStateException("SMTP mail server is not configured in Jira")
}
def email = new Email("recipient@example.com") // Replace with the recipient's email
email.setSubject("Jira Filter Results CSV Report")
email.setBody("Please find the attached CSV report for filter ID ${filterId}.")
email.addAttachment("jira_filter_${filterId}_issues.csv", new File(outputFilePath))
// Send the email
mailServer.send(email)
logger.warn "Email sent successfully to recipient@example.com"
You must be a registered user to add a comment. If you've already registered, sign in. Otherwise, register and sign in.