Come for the products,
stay for the community

The Atlassian Community can help you and your team get more value out of Atlassian products and practices.

Atlassian Community about banner
Community Members
Community Events
Community Groups

Scriptrunner JQL Search Cache



I am attempting to create a script to verify the health of our email system. We have a number of mail handlers and so I am creating a Scriptrunner job to automate the following health check process.

Send email -> Wait -> Search for issue -> Delete Issue

The search for issue is a loop that runs a jql every X seconds for X minutes. If the issue never arrives then an error is logged.


The Problem: The JQL query never seems to find the issue. When I search in the UI, I can find the issue. When I create a search to find an issue that is already in the system, it will find and delete the issue. However it seems the script cannot find issues that are created after the script has started. What can I do?


// Import required classes
import com.atlassian.mail.server.MailServerManager
import com.atlassian.mail.Email;
import com.atlassian.jira.component.ComponentAccessor
import com.atlassian.jira.event.type.EventDispatchOption
import com.atlassian.jira.util.ErrorCollection
import com.atlassian.jira.issue.Issue
import com.atlassian.jira.bc.issue.IssueService
import com.atlassian.jira.bc.issue.IssueService.DeleteValidationResult
import com.atlassian.jira.jql.parser.JqlQueryParser
import com.atlassian.jira.web.bean.PagerFilter
import java.time.LocalDateTime;
import java.sql.Timestamp;
import org.apache.log4j.Logger
import org.apache.log4j.Level

// Script Configuration
final int retrySeconds = 30
final int retryAttempts = 20

// Classes
class Mailbox {
String emailAddress;
String project;
long emailSent;
long emailFound;

// Methods
def sendEmail(String emailAddr, String subject, String body){
def mailServer = ComponentAccessor.getMailServerManager().getDefaultSMTPMailServer()

if (mailServer){
Email email = new Email(emailAddr)

final Long testTime = Timestamp.valueOf(
String subjectKey = "Automated Test: ${testTime}"
List<Mailbox> mailboxes = []

Mailbox newMailbox = new Mailbox(emailAddress: "INSERT_EMAIL_HERE", project: "INSERT_PROJECT_KEY")

mailboxes += newMailbox"Automated Email Health: Beginning Health Checks on ${mailboxes.size()} with key ${testTime}")

mailboxes.each{ mailbox ->
mailbox.emailSent = testTime
sendEmail(mailbox.emailAddress, subjectKey, "This is an automated test message.")
log.debug("Automated Email Health: Sending email to ${mailbox.emailAddress} with key ${testTime}")

IssueService issueService = ComponentAccessor.getIssueService()
SearchService searchService = ComponentAccessor.getComponent(SearchService)
def jqlQueryParser = ComponentAccessor.getComponent(JqlQueryParser)
def issueManager = ComponentAccessor.getIssueManager()
def user = ComponentAccessor.getJiraAuthenticationContext().getLoggedInUser()

boolean success = false
int retries = 0
List<Mailbox> failures = []

while (!success && retries < retryAttempts){
Thread.sleep(retrySeconds * 1000)
success = true
failures = []

log.debug("Automated Email Health: Beginning attempt ${retries}")

mailboxes.each{ mailbox ->
if (!mailbox.emailFound){
def query = jqlQueryParser.parseQuery("project = '${mailbox.project}' AND creator = shadmin AND created >= -30m AND summary ~ '${subjectKey}'")
def results =, query, PagerFilter.getUnlimitedFilter())
if ( results.getTotal() < 1 ){
success = false;
failures += mailbox
log.debug("Automated Email Health: Did not find issue for project ${mailbox.project} on attempt ${retries}")
}else if ( results.getTotal() == 1 ){
mailbox.emailFound = Timestamp.valueOf(
def documentIssue = results.getResults()[0]
DeleteValidationResult deleteValidationResult = issueService.validateDelete(user,
if (deleteValidationResult.isValid()){
log.debug("Automated Email Health: Deleting issue ${documentIssue.key}")
ErrorCollection deleteResult = issueService.delete(user, deleteValidationResult);
if (deleteResult.hasAnyErrors()){
log.error("Automated Email Health: Errors while trying to delete issue.")
log.error("Automated Email Health: Unable to delete issue. Reason: ${deleteValidationResult.getErrorCollection()}")
log.error("Automated Email Health: More than one issue found matching '${query}' this could mean that the mail handler is duplicating emails")

if (!success){
log.error("Automated Email Health: Failed to retrieve emails for one or more mailboxes")
failures.each{ mailbox ->
log.error("Automated Email Health: Unable to retrieve email for ${mailbox.project} from ${mailbox.emailAddress}")

int completionTime = (int) ((Timestamp.valueOf( - testTime) / 60)"Automated Email Health: Completed Health Checks in ${completionTime} seconds")

return "Success: ${success} in ${completionTime} seconds"


1 answer

if you use

log.error "project = '${mailbox.project}' AND creator = shadmin AND created >= -30m AND summary ~ '${subjectKey}'"

 before search result. and copy in jql search in ui is it correct search?

Suggest an answer

Log in or Sign up to answer
Community showcase
Published in Jira

Online AMA this week: Your project management questions answered by Jira Design Lead James Rotanson

We know that great teams require amazing project management chops. It's no surprise that great teams who use Jira have strong project managers, effective workflows, and secrets that bring planning ...

205 views 1 6
Read article

Atlassian Community Events