Created an email handler using Scriprunner's Incoming Email handler code. It takes data from the email and creates a ticket.
I would like to take the actual email that the Email handler is parsing and add it as an attachment to the ticket.
The attachment examples are for taking the email's attachments, I need to attach the original email that is being parsed by the Email handler.
Hi @Jon Kocen
For your requirement you can try something like this:-
import com.atlassian.jira.component.ComponentAccessor
import com.atlassian.jira.config.util.JiraHome
import com.atlassian.jira.event.type.EventDispatchOption
import com.atlassian.jira.issue.MutableIssue
import com.atlassian.jira.issue.attachment.CreateAttachmentParamsBean
import com.atlassian.jira.service.services.file.FileService
import com.atlassian.jira.service.util.ServiceUtils
import com.atlassian.jira.service.util.handler.MessageUserProcessor
import com.atlassian.mail.MailUtils
import javax.mail.Message
import javax.mail.internet.InternetAddress
import javax.mail.internet.MimeBodyPart
import javax.mail.internet.MimeMessage
import javax.mail.internet.MimeMultipart
def userManager = ComponentAccessor.userManager
def projectManager = ComponentAccessor.projectManager
def issueManager = ComponentAccessor.issueManager
def attachmentManager = ComponentAccessor.attachmentManager
def issueFactory = ComponentAccessor.issueFactory
def messageUserProcessor = ComponentAccessor.getComponent(MessageUserProcessor)
def jiraHome = ComponentAccessor.getComponent(JiraHome)
def user = userManager.getUserByName("admin")
def reporter = messageUserProcessor.getAuthorFromSender(message) ?: user
def project = projectManager.getProjectObjByKey("MOCK")
def subject = message.subject
def from = message.from.join(',')
def to = message.allRecipients.join(',')
def messageBody = MailUtils.getBody(message)
static Message createMessage(String from, String to, String subject, String content) {
def msg = new MimeMessage(null)
msg.setFrom(new InternetAddress(from))
msg.setRecipient(Message.RecipientType.TO, new InternetAddress(to))
msg.setSubject(subject)
def body = new MimeBodyPart()
body.setText(content)
msg.setContent(new MimeMultipart(body))
msg
}
def issue = ServiceUtils.findIssueObjectInString(subject) as MutableIssue
if (issue) {
return
}
def issueObject = issueFactory.issue
issueObject.setProjectObject(project)
issueObject.setSummary(subject)
issueObject.setDescription(messageBody)
issueObject.setIssueTypeId(project.issueTypes.find { it.name == 'Bug' }.id)
issueObject.setReporter(reporter)
issue = messageHandlerContext.createIssue(user, issueObject) as MutableIssue
def destination = new File(jiraHome.home, FileService.MAIL_DIR).absoluteFile
def file = new File("${destination}/tempMail.eml")
file.createNewFile()
def out = new FileOutputStream(file)
def emailContent = createMessage(from, to, subject, messageBody)
emailContent.writeTo(out)
def attachmentParams = new CreateAttachmentParamsBean.Builder("${destination}/${file.absoluteFile.name}" as File, 'SampleMail.eml' , '', user, issue).build()
attachmentManager.createAttachment(attachmentParams)
issueManager.updateIssue(user, issue, EventDispatchOption.DO_NOT_DISPATCH,false)
file.delete()
Please note, the sample working provided is not 100% exact to your environment. Hence, you will need to make the required modifications.
What this code does is that it uses the Mail Handler to create a new ticket, and at the same time, when that process is being carried out, the content of the email is extracted and saved into another file.
In this example, it is saved as a .eml file, i.e. an exported email, and added to Jira's import mail folder, i.e. <JIRA_HOME>/application-data/jira/import/mail. You will need to modify this according to your requirement.
Once the ticket is created, the email file is added as an attachment to the ticket.
Below are a few test screens for your reference:-
1) When the Mail Handler creates the issue, the .eml file attachment is included as shown below:-
2) To open the file, the file needs to be downloaded first as shown below:-
3) Once the file has been downloaded, it can be opened with a mail application. For example, using Mozilla's Thunderbird as shown in the image below:-
I hope this helps to answer your question. :)
Thank you and Kind Regards,
Ram
How would one go about doing something similar in Jira Cloud (SM)?
I have read that HAPI would have a addAttachment() but at least the inline editor say it doesn't exist. Or is that just a IDE misconfiguration?
I also have a need to copy attachment from a parent.
You must be a registered user to add a comment. If you've already registered, sign in. Otherwise, register and sign in.
You can store the email file in memory an then upload it to the issue
InputStream inputStream = emailResponse.body
def fileName = "${log.mailItemId}.eml"
if (inputStream) {
// Attach the file directly to Jira
def attachmentResponse = post("/rest/api/3/issue/${issueKey}/attachments")
.header('X-Atlassian-Token', 'no-check')
.field("file", inputStream, fileName)
.asString()
if (attachmentResponse.status == 200) {
logger.info("Email file attached successfully: ${fileName}")
} else {
logger.info("Failed to attach email file: ${fileName}. Status: ${attachmentResponse.status}, Response: ${attachmentResponse.body}")
}
} else {
logger.info("Email download failed: InputStream is null for ${emailDownloadLink}")
}
} catch (Exception e) {
logger.info("Error downloading or attaching email: ${e.message}")
}
}
You must be a registered user to add a comment. If you've already registered, sign in. Otherwise, register and sign in.
Online forums and learning are now in one easy-to-use experience.
By continuing, you accept the updated Community Terms of Use and acknowledge the Privacy Policy. Your public name, photo, and achievements may be publicly visible and available in search engines.
You must be a registered user to add a comment. If you've already registered, sign in. Otherwise, register and sign in.