In this blog post, I’ll walk you through the process of using ScriptRunner to send emails with attachments, enhancing your Jira automation capabilities.

Getting Started

Before we dive into the code, ensure that you have ScriptRunner for Jira installed in your instance. ScriptRunner is a powerful scripting tool that allows you to customize and automate tasks in Jira.

Writing the Script

Let’s start by creating a script that sends an email with attachments. Below is a sample Groovy script you can use:

import com.atlassian.jira.component.ComponentAccessor
import com.atlassian.jira.issue.attachment.Attachment
import com.atlassian.mail.Email
import com.atlassian.mail.queue.SingleMailQueueItem
import javax.mail.*
import javax.mail.internet.*

void sendEmail(String emailAddr, String copy, String subject, String body, Optional<String> from, Optional<String> replyTo, String emailFormat, Collection<Attachment> attachments) {
    Email email = new Email(emailAddr)
    email.setSubject(subject)
    email.setCc(copy) // 'copy' is for CC recipients
    email.setFrom(from.orElse(null)) // Use 'orElse' to set default sender
    email.setReplyTo(replyTo.orElse(null))
    email.setMimeType("multipart/mixed")

    Multipart multipart = new MimeMultipart("mixed")
    MimeBodyPart bodyPart = new MimeBodyPart()
    bodyPart.setContent(body, emailFormat + "; charset=utf-8")
    multipart.addBodyPart(bodyPart)

    // Add attachments to the email
    attachments.each { Attachment attachment ->
        File file = ComponentAccessor.getAttachmentManager().getAttachmentFile(attachment)
        MimeBodyPart attachmentPart = new MimeBodyPart()
        attachmentPart.attachFile(file, attachment.getMimetype(), null)
        attachmentPart.setFileName(attachment.getFilename())
        multipart.addBodyPart(attachmentPart)
    }
    
    email.setMultipart(multipart)
    SingleMailQueueItem smqi = new SingleMailQueueItem(email)
    ComponentAccessor.getMailQueue().addItem(smqi)
}

// Usage example:
def emailAddr = "example@example.com" // The email recipient
def copy = "" // The email copy recipients, separated by commas
def subject = "Email subject" // The email subject
def body = "Email body" // The email body
def from = Optional.ofNullable(null) // The email sender address, default is Jira address
def replyTo = Optional.ofNullable(null) // The email reply-to address
def emailFormat = "text/html" // The email format, default is HTML
def attachments = issue.getAttachments()

sendEmail(emailAddr, copy, subject, body, from, replyTo, emailFormat, attachments)

Using the Script

To use the script, replace the example parameters (emailAddr , subject, body) with your desired values. Then, execute the script in the Script Console provided by ScriptRunner for Jira.

With this script, you can now automate the process of sending emails with attachments in your Jira Server or Data Center instance, streamlining your workflow and improving communication within your team.

That’s it!