Create
cancel
Showing results for 
Search instead for 
Did you mean: 
Sign up Log in
It's not the same without you

Join the community to find out what other Atlassian users are discussing, debating and creating.

Atlassian Community Hero Image Collage

How can I create an attachment to an issue in a post-function?

Hi. The problem:

I need to generate attachment based on summary and description on create transaction.

For example exactly after moment when user create issue. Attache should appear after issue was created.

Attach could be like some Html/DOCx/RTF document which contain some template filled information based on description, summary and some CF.

May be some one have example how to make this in scriptrunner.

 

1 answer

1 accepted

1 vote
Answer accepted

My own solution

 

import com.atlassian.jira.component.ComponentAccessor
import com.atlassian.jira.issue.attachment.CreateAttachmentParamsBean
import com.atlassian.jira.issue.Issue
import com.atlassian.jira.issue.IssueManager
import java.time.*


def attachmentManager = ComponentAccessor.getAttachmentManager()

def user = ComponentAccessor.getJiraAuthenticationContext()?.getUser()

def Reporter = issue.getReporter() as String
def Desc = issue.getDescription()


LocalDateTime CurrentTime = LocalDateTime.now();

def String filename = "1.html"
def Template = """
<!DOCTYPE html>
<html>
<head>
<title>Some title</title>
</head>
<body>
<p style="text-align:right">From ${Reporter}</p>

<p style="text-align:right">NAME</p>

<p>&nbsp;</p>

<p>&nbsp;</p>

<p style="text-align:center"><strong>Some Main TEXT</strong></p>

<p>&nbsp;</p>

<p>${Desc}</p>

<p>&nbsp;</p>

<p><strong>Date ${CurrentTime}</strong></p>
</body>
</html>


"""

File f = new File("/tmp/"+filename);

f.getParentFile().mkdirs();
f.createNewFile();


FileWriter fw = new FileWriter("/tmp/"+filename, true)
BufferedWriter bw = new BufferedWriter(fw)
PrintWriter out = new PrintWriter(bw)

out.println(Template);

out.close()

def bean = new CreateAttachmentParamsBean.Builder()
.file(f)
.filename(filename)
.contentType("text/plain")
.author(user)
.issue(issue)
.build()
attachmentManager.createAttachment(bean)

Hi @Ilya Stekolnikov 

where did you apply that script ? in send custom email postfunction ?

hi @Samar Elsayed  - i just used it at regular post-function. Script generate attach inside issue.

Thanks @Ilya Stekolnikov 

I can see email template but I dont see the part where you send that email.

why I am asking that is that I want to create an attachment that contain a result from script and then send that attachment by email in postfunction but I dont know how to do that.

ok, i am understand you. In my script i generate attach inside issue. i didn`t send it with e-mail. So you can use my script for generate attach, and add next post-function just for sending e-mail. I think you will understand me, just use this script in post function and you will understand how it works.

@Ilya Stekolnikov  Thank you so much, one last question :

 

when I use /tmp/ as the path for the attachment , run the script and go to /tmp/ on jira server I can see one file but when I delete the attachment from the issue and rerun my script , I can still see only the same old file there on the server and also when I delete that file from /tmp/ and rerun the script, the new attachment is created successfully in the issue but I cant find it in /tmp/

 

can you explain to me why this is happening and where can I find these attachments on jira server?

 

Thanks

import com.atlassian.jira.component.ComponentAccessor
import com.atlassian.jira.issue.AttachmentManager
import com.atlassian.jira.issue.IssueManager
import com.atlassian.jira.issue.MutableIssue
import com.atlassian.jira.issue.attachment.Attachment
import com.atlassian.jira.issue.search.SearchProvider
import com.atlassian.jira.user.ApplicationUser
import com.atlassian.jira.user.util.UserManager
import com.atlassian.jira.util.AttachmentUtils
import org.apache.log4j.Logger
import org.slf4j.MDC
import java.nio.file.Files
import com.atlassian.jira.bc.issue.IssueService
import com.atlassian.query.Query
import com.atlassian.jira.issue.search.SearchResults
import com.atlassian.jira.jql.parser.JqlQueryParser
import com.atlassian.jira.bc.issue.search.SearchService
import com.atlassian.jira.web.bean.PagerFilter
import com.atlassian.jira.jql.parser.*
import java.lang.*
import com.atlassian.jira.issue.IssueInputParameters
import java.util.ArrayList
import com.atlassian.jira.util.ImportUtils
import com.atlassian.jira.util.JiraUtils
import com.atlassian.jira.workflow.WorkflowTransitionUtilImpl
import com.atlassian.jira.workflow.TransitionOptions
import java.util.List

IssueManager issueManager = ComponentAccessor.getIssueManager();
UserManager userManager = ComponentAccessor.getUserManager();
AttachmentManager attachmentManager = ComponentAccessor.getAttachmentManager();
IssueService issueService = ComponentAccessor.getComponent(IssueService)

ApplicationUser actingUser = ComponentAccessor.jiraAuthenticationContext.loggedInUser
def jqlQueryParser = ComponentAccessor.getComponent(JqlQueryParser)
def searchService = ComponentAccessor.getComponent(SearchService)
String jqlSearch = "key in (dias-1, dias-8)"

Query query = jqlQueryParser.parseQuery(jqlSearch)
SearchResults results = searchService.search(actingUser,query, PagerFilter.getUnlimitedFilter())
if (results.total == 0) { //если результат 0 не идем дальше
return
}

ArrayList issues = results.results.collect {issueManager.getIssueObject (it.id)} //ArrayList с результатом поиска
issues.each { issue ->
MutableIssue curIssue = issueManager.getIssueObject(issue.id)
String date = new Date().format('dd-MM-yyyy', TimeZone.getTimeZone('BST')) //текущая дата и время
String folderName = date //название будущей папки в директории (название проекта + номер заявки + текущая дата)
String folderName2 = curIssue.getKey()
List<Attachment> attachmentList = attachmentManager.getAttachments(curIssue); //List с вложениями текущего issue в цикле по перебору результата jql
for(Attachment attachment:attachmentList) { // цикл по перебору вложении по issue
String attachmentFileName = attachment.getFilename(); //получение Filename вложения
File attachmentFile = AttachmentUtils.getAttachmentFile(attachment)
byte[] encodedFile = Files.readAllBytes(attachmentFile.toPath()); //Файл в байт
new File("/opt/atlassian/application-data/jira/testAttachment/${folderName}").mkdir() //создание папки в директории

new File("/opt/atlassian/application-data/jira/testAttachment/${folderName}/${folderName2}").mkdir() //создание папки в директории

String fileNewFullPath = "/opt/atlassian/application-data/jira/testAttachment/${folderName}/${folderName2}/"+ attachmentFileName; //String с Path
try {
OutputStream stream = new FileOutputStream(fileNewFullPath) //запись байтов в файл
stream.write(encodedFile);
stream.close();
} catch(Exception e){
log.warn(e.getMessage())
}
}

}

 @Samar Elsayed  May be this one can help you. This script find all attachments in issues from JQL Result and copy them in some folder at server.

Suggest an answer

Log in or Sign up to answer
DEPLOYMENT TYPE
SERVER
TAGS
Community showcase
Published in Jira Software

👋 Looking for 15-20 volunteers to test Atlassian training content

Hi everyone! Are you interested in beta testing Atlassian University’s newest (unreleased!) training course? We’re looking for 15-20 volunteers to test our newest training course, Basic reporting...

745 views 23 27
Read article

Community Events

Connect with like-minded Atlassian users at free events near you!

Find an event

Connect with like-minded Atlassian users at free events near you!

Unfortunately there are no Community Events near you at the moment.

Host an event

You're one step closer to meeting fellow Atlassian users at your local event. Learn more about Community Events

Events near you