Forums

Articles
Create
cancel
Showing results for 
Search instead for 
Did you mean: 

How to write a groovy script to send email subscriptions with attached filter results (as CSV)

Udara Manupriya January 9, 2025

When try to send the filtered results and send them via "subscription Emails" Results are sending as in email body (not as a CSV/Excel attachment in the mail) I need to send that as csv attachment in the email I need to do this using a groovy script. Can anyone please help me on that

My approach is like below. If anyone knows a better approach please let me also.

  • Step 1 -> JQL results convert to CSV using a groovy script.
  • Step 2 -> Create a groovy script to send the subscription emails by attaching csv file created in step 1

1 answer

2 votes
Sahir Maharaj
Rising Star
Rising Star
Rising Stars are recognized for providing high-quality answers to other users. Rising Stars receive a certificate of achievement and are on the path to becoming Community Leaders.
January 11, 2025

Hello @Udara Manupriya

From my limited understanding, sending Jira filter results as a CSV attachment via a Groovy script involves two key steps: generating the CSV from JQL and attaching it to an email. To generate the CSV, you can use Jira’s API to query results and format them into a CSV file. Then, use a Groovy mail library like javax.mail to send the email with the CSV file attached.

If you encounter challenges with script implementation, Atlassian’s ScriptRunner documentation offers examples that can help. For advanced assistance or validation of your script, you can also reach out to Atlassian support at https://support.atlassian.com/contact/#/.

Udara Manupriya January 14, 2025

Thank you @Sahir Maharaj 

Like Sahir Maharaj likes this
Udara Manupriya January 15, 2025

Hi @Sahir Maharaj

I have created a groovy script , JQL results are successfully exported as csv but when I try to send emails, the imported below  libraries are not resolved

import com.atlassian.mail.Email

import com.atlassian.mail.server.SMTPMailServer
import com.atlassian.jira.component.ComponentAccessor

My entire groovy script as below

 

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"

Suggest an answer

Log in or Sign up to answer
DEPLOYMENT TYPE
CLOUD
PRODUCT PLAN
PREMIUM
TAGS
AUG Leaders

Atlassian Community Events