Just a heads up: On March 24, 2025, starting at 4:30pm CDT / 19:30 UTC, the site will be undergoing scheduled maintenance for a few hours. During this time, the site might be unavailable for a short while. Thanks for your patience.
×Hi All,
is it possible to get the list of inactive users of JIRA by jelly or groovy?
Note, I do not have access to DB so SQL is not possible.
Thanks in advance,
Rumi
Yes.
import com.atlassian.jira.component.ComponentAccessor import com.atlassian.jira.user.util.UserManager UserManager userManager = ComponentAccessor.getUserManager() userManager.getUsers().findAll{user -> !user.isActive()}.each { user -> //... }
Hello Henning,
Can we get list of inactive users for specific time, like I need list of users who are inactive from last 30 days?
Regards,
You must be a registered user to add a comment. If you've already registered, sign in. Otherwise, register and sign in.
Hi,
if you define inactive as "not logged in" you can use something like this.
import com.atlassian.jira.component.ComponentAccessor def crowdService = ComponentAccessor.crowdService def ofBizUserDao = ComponentAccessor.getComponent(OfBizUserDao) def userUtil = ComponentAccessor.userUtil def dateLimit = (new Date()) - 30 userUtil.getUsers().findAll { it.isActive() }.each { def user = crowdService.getUserWithAttributes(it.getName()) def lastLoginMillis = user.getValue('login.lastLoginMillis') if (!lastLoginMillis?.isNumber()) { def tu = ofBizUserDao.findByName(user.directoryId, user.name) lastLoginMillis = tu.getCreatedDate()?.time } if (lastLoginMillis) { def d = new Date(Long.parseLong(lastLoginMillis)) if (d.before(dateLimit)) { // not logged in for 30 days... } } }
If the user never was logged in, this uses the created date for calculating the time of "inactivity".
Henning
You must be a registered user to add a comment. If you've already registered, sign in. Otherwise, register and sign in.
You must be a registered user to add a comment. If you've already registered, sign in. Otherwise, register and sign in.
Ah, I missed an import while copying..
import com.atlassian.jira.crowd.embedded.ofbiz.OfBizUserDao
You must be a registered user to add a comment. If you've already registered, sign in. Otherwise, register and sign in.
And you have to do something at the position of the comment (// blue), like
import com.atlassian.jira.component.ComponentAccessor import com.atlassian.jira.crowd.embedded.ofbiz.OfBizUserDao def crowdService = ComponentAccessor.crowdService def ofBizUserDao = ComponentAccessor.getComponent(OfBizUserDao) def userUtil = ComponentAccessor.userUtil def dateLimit = (new Date()) - 30 def result = "" userUtil.getUsers().findAll { it.isActive() }.each { def user = crowdService.getUserWithAttributes(it.getName()) String lastLoginMillis = user.getValue('login.lastLoginMillis') if (!lastLoginMillis?.isNumber()) { def tu = ofBizUserDao.findByName(user.directoryId, user.name) lastLoginMillis = tu.getCreatedDate()?.time } if (lastLoginMillis) { def d = new Date(Long.parseLong(lastLoginMillis)) if (d.before(dateLimit)) { // not logged in for 30 days... result += "${user.displayName} (${user.name})<br>" } } } result
to print a list of "inactive" users.
Please note the change to String lastLoginMillis, otherwise you'll get a runtime error.
Henning
You must be a registered user to add a comment. If you've already registered, sign in. Otherwise, register and sign in.
You must be a registered user to add a comment. If you've already registered, sign in. Otherwise, register and sign in.
I can't seem to comment on this, it says I'm a spammer :(
There it goes, now for my actual comment:
Does this need to be revised? I'm getting
Cannot invoke method findByName() on null object.
Thanks!
You must be a registered user to add a comment. If you've already registered, sign in. Otherwise, register and sign in.
There were some changes in JIRA 7. Here's my current script to deactivate inactive users:
import com.atlassian.crowd.embedded.api.UserWithAttributes
import com.atlassian.crowd.embedded.spi.UserDao
import com.atlassian.jira.application.ApplicationAuthorizationService
import com.atlassian.jira.application.ApplicationKeys
import com.atlassian.jira.bc.user.ApplicationUserBuilderImpl
import com.atlassian.jira.bc.user.UserService
import com.atlassian.jira.bc.user.search.UserSearchParams
import com.atlassian.jira.bc.user.search.UserSearchService
import com.atlassian.jira.component.ComponentAccessor
def test = true // to really deactivate users, change to false
int numOfDays = 182 // Number of days the user was not logged in
def blockedUsers = // User who should not be deactivated
[
'administrator'
]
def maximumNumberOfUsers = 10000 // search is restricted to find at max this number of users
def userSearchService = ComponentAccessor.getComponent(UserSearchService)
def crowdService = ComponentAccessor.crowdService
def userService = ComponentAccessor.getComponent(UserService.class)
def userDao = ComponentAccessor.getComponent(UserDao)
def applicationAuthorizationService = ComponentAccessor.getComponent(ApplicationAuthorizationService)
def updateUser
def updateUserValidationResult
Date dateLimit = (new Date()) - numOfDays
String result = ""
def userSearchParamsBuilder = new UserSearchParams.Builder()
userSearchParamsBuilder
.allowEmptyQuery(true)
.ignorePermissionCheck(true)
.maxResults(maximumNumberOfUsers)
def allActiveUsers = userSearchService.findUsers("", userSearchParamsBuilder.build())
result += "All active Users: ${allActiveUsers.size()}<br>"
allActiveUsers.findAll {
!blockedUsers.contains(it.name) &&
(
applicationAuthorizationService.canUseApplication(it, ApplicationKeys.SOFTWARE) ||
applicationAuthorizationService.canUseApplication(it, ApplicationKeys.SERVICE_DESK)
)
}.each { appUser ->
UserWithAttributes user = crowdService.getUserWithAttributes(appUser.getName())
String lastLoginMillis = user.getValue('login.lastLoginMillis')
def start_text = "Last Login was"
if (!lastLoginMillis?.isNumber()) {
if (user.directoryId && user.name) {
def tu = userDao.findByName(user.directoryId, user.name)
lastLoginMillis = tu?.getCreatedDate()?.time
start_text = "Not logged in, created on"
} else {
start_text = "SOMETHING WRONG: $user.directoryId && $user.name"
}
}
if (lastLoginMillis) {
Date d = new Date(Long.parseLong(lastLoginMillis))
if (d.before(dateLimit)) {
updateUser = (new ApplicationUserBuilderImpl(appUser)).active(false).build()
updateUserValidationResult = userService.validateUpdateUser(updateUser)
if (updateUserValidationResult.isValid()) {
if (!test) {
userService.updateUser(updateUserValidationResult)
}
result += "Deactivated ${updateUser.name} - $start_text ${d.format("dd.MM.yyyy hh:mm")}"
} else {
result += "Update of ${updateUser.displayName} (${updateUser.name}) failed: ${updateUserValidationResult.getErrorCollection().getErrors().entrySet().join(',')}"
}
}
}
}
result
Henning
You must be a registered user to add a comment. If you've already registered, sign in. Otherwise, register and sign in.
Hi Henning
Regarding your script for JIRA 7. What would be the script if I nly need to display user who did not login in the last 60 days without deactivationg them.
Thanks for your help,
Elvir
You must be a registered user to add a comment. If you've already registered, sign in. Otherwise, register and sign in.
Hi Elvir,
just exchange the inner part of if (d.before(dateLimit)):
if (d.before(dateLimit)) {
result += "Inactive user: ${appUser.name} - $start_text ${d.format("dd.MM.yyyy hh:mm")}<br>"
}
Henning
You must be a registered user to add a comment. If you've already registered, sign in. Otherwise, register and sign in.
Can we use this groovy script with cloud script runner to get the inactive users and projects?
You must be a registered user to add a comment. If you've already registered, sign in. Otherwise, register and sign in.
Hi Henning, is it possible to deactivated user by using name for any position like team lead, administrator. Thanks for your time.
You must be a registered user to add a comment. If you've already registered, sign in. Otherwise, register and sign in.
Hi Asif, I don't understand your question. What do you mean with "position"? The script could deactivate every user, as long as this user is not component or project lead in any project.
You must be a registered user to add a comment. If you've already registered, sign in. Otherwise, register and sign in.
Hi Henning,
I have written a groovy script to deactivate users. The issue I am running into is that the script will fail if the user is a component lead or project lead. What I want to do is check if the user is a component lead and remove them if they are. So far I have been struggling to do so. (My current version of Jira 8.1.1)
Any help would be much appreciated.
You must be a registered user to add a comment. If you've already registered, sign in. Otherwise, register and sign in.
Ah, ok, understand. Try to integrate this into your script:
import com.atlassian.jira.bc.project.component.MutableProjectComponent
import com.atlassian.jira.component.ComponentAccessor
import com.atlassian.jira.project.UpdateProjectParameters
import com.atlassian.jira.user.ApplicationUser
def userUtil = ComponentAccessor.userUtil
def projectManager = ComponentAccessor.projectManager
def projectComponentManager = ComponentAccessor.projectComponentManager
ApplicationUser user // the user who should be deactivated
ApplicationUser replacementUser // the user who should be used as project/component lead instead
// Check if user is component lead
def components = userUtil.getComponentsUserLeads(user)
components?.each{ component ->
def mutProjComp = MutableProjectComponent.copy(component)
mutProjComp.setLead(replacementUser?.name)
projectComponentManager.update(mutProjComp)
}
// Check if user is project lead
def projects = userUtil.getProjectsLeadBy(user)
projects?.each{project ->
def updateProjectParameters = UpdateProjectParameters.forProject(project.id).leadUserKey(replacementUser?.key)
projectManager.updateProject(updateProjectParameters)
}
You must be a registered user to add a comment. If you've already registered, sign in. Otherwise, register and sign in.
Hi Henning
Thanks for your prompt response. I tried to integrate your code in my script but still its not working. Could you please give me the full script.
Thanks in advance.
You must be a registered user to add a comment. If you've already registered, sign in. Otherwise, register and sign in.
Hi Asif,
I would suggest you post your script and the error you get and I will help you to get it going.
Best, Henning
You must be a registered user to add a comment. If you've already registered, sign in. Otherwise, register and sign in.
Hi Henning,
I would like to do remove/deactivate Project Lead, Component Lead from the project who aren't available in project and replace them automatically with current Project Lead, Component Lead. (Jira v8.1.1)
I will be grateful for any help you can provide.
You must be a registered user to add a comment. If you've already registered, sign in. Otherwise, register and sign in.
Hi Asif,
how do you define "aren't available in project" and "current Project Lead, Component Lead"?
Best,
Henning
You must be a registered user to add a comment. If you've already registered, sign in. Otherwise, register and sign in.
Hi Henning,
Actually what I want to do is check if the user is a component lead/ project lead and who isn't anymore in project/company remove them automatically and replace another project lead/ component lead in this place. Any help would be much appreciated.
Thanks for your time
You must be a registered user to add a comment. If you've already registered, sign in. Otherwise, register and sign in.
Hi Asif,
mmh, ok, so that's the same as in December. You should combine the scripts from comments from Aug 09, 2017 and Dec 17, 2019 • edited. If you get an error after doing this, you can post your combined script here and I'll take a look what's wrong.
Best,
Henning
You must be a registered user to add a comment. If you've already registered, sign in. Otherwise, register and sign in.
Hi Henning,
I'm trying to combine with this script but it shows error. Could you please tell what can I do.
Thanks a lot for your help
import com.atlassian.jira.bc.project.component.MutableProjectComponent
import com.atlassian.jira.component.ComponentAccessor
import com.atlassian.jira.project.UpdateProjectParameters
import com.atlassian.jira.user.ApplicationUser
import com.atlassian.crowd.embedded.impl.ImmutableUser
import com.atlassian.jira.bc.project.component.MutableProjectComponent
import com.atlassian.jira.bc.user.UserService
import com.atlassian.jira.component.ComponentAccessor
import com.atlassian.jira.user.DelegatingApplicationUser
def userService = ComponentAccessor.getComponent(UserService.class)
def userName = "..."
def userUtil = ComponentAccessor.userUtil
def projectManager = ComponentAccessor.projectManager
def projectComponentManager = ComponentAccessor.projectComponentManager
def User
ApplicationUser user // the user who should be deactivated
ApplicationUser replacementUser // the user who should be used as project/component lead instead
// Check if user is component lead
def components = userUtil.getComponentsUserLeads(user)
components?.each{ component ->
def mutProjComp = MutableProjectComponent.copy(component)
mutProjComp.setLead(replacementUser?.name)
projectComponentManager.update(mutProjComp)
}
// Check if user is project lead
def projects = userUtil.getProjectsLeadBy(user)
projects?.each{project ->
def updateProjectParameters = UpdateProjectParameters.forProject(project.id).leadUserKey(replacementUser?.key)
projectManager.updateProject(updateProjectParameters)
}
if (!componentsLeadedBy && !projectLeadedBy)
log.info "userName doesn't lead any component or project"
else {
//remove userName from project lead roles
if (projectLeadedBy.size() > 0)
for (project in projectLeadedBy) {
projectManager.updateProject(project, project.name, project.description, "", project.url, project.assigneeType);
}
//remove userName from component lead roles
if (componentsLeadedBy.size() > 0)
for (component in componentsLeadedBy) {
MutableProjectComponent newComponent = MutableProjectComponent.copy(component)
newComponent.setLead("")
projectComponentManager.update(newComponent)
}
}
def listUsers = userManager.getUsers().findAll{user -> user.name.equals(userName)}
if (listUsers.size() > 0)
return "User userName does not exist"
ImmutableUser.Builder builder = ImmutableUser.newUser(listUsers[0]);
builder.active(false);
def updatedUser = new DelegatingApplicationUser(applicationUser.key, builder.toUser())
UserService.UpdateUserValidationResult updateUserValidationResult =
userService.validateUpdateUser(updatedUser)
if (updateUserValidationResult.isValid()) {
userService.updateUser(updateUserValidationResult)
return "User ${applicationUser.name} deactivated";
} else {
return updateUserValidationResult.getErrorCollection()
}
You must be a registered user to add a comment. If you've already registered, sign in. Otherwise, register and sign in.
Hi Asif,
you have to get a user first before you try to determine if the user is a component lead etc. This part is missing before the first use auf "user".
You must be a registered user to add a comment. If you've already registered, sign in. Otherwise, register and sign in.
Hi @Henning Tietgens
I was also looking for a solution to check the inactive users
I am able to connect to Jira from a Groovy script, I am successful at connecting and sending jql statements, however I dont have the below classes, are the below free classes and can be downloaded from somewhere if free or do they need licenses ?
import com.atlassian.jira.component.ComponentAccessor
import com.atlassian.jira.user.util.UserManager
You must be a registered user to add a comment. If you've already registered, sign in. Otherwise, register and sign in.
Hi,
The classes are supplied by Jira itself. You need to run the script from the Script Console provided by Script Runner.
You must be a registered user to add a comment. If you've already registered, sign in. Otherwise, register and sign in.
Hi Henning,
But I am running from a remote box. So, I thought I can have a a jar file in the classpath ? I dont have the Jira script console in this box.
You must be a registered user to add a comment. If you've already registered, sign in. Otherwise, register and sign in.
The script console can be opened from within Jira. You don't need direct access to the server. Try /plugins/servlet/scriptrunner/admin/console on your Jira web address.
You must be a registered user to add a comment. If you've already registered, sign in. Otherwise, register and sign in.
Hi @Henning Tietgens can you please me with the script for getting the list of users in jira Name, Email Address, and active and in active users list and created , last updated date in a single script? is that possible to get all these details in a single script? please help me in this thank you in advance
You must be a registered user to add a comment. If you've already registered, sign in. Otherwise, register and sign in.
Hi Murty,
try this
import com.atlassian.crowd.embedded.spi.UserDao
import com.atlassian.jira.component.ComponentAccessor
def userManager = ComponentAccessor.userManager
def userDao = ComponentAccessor.getComponent(UserDao)
result = "Name\tEmail\tActive\tCreated\tUpdated\n"
userManager.getAllUsers().each { u ->
def uo = userDao.findByName(u.directoryId, u.name)
def created = uo?.getCreatedDate()
def updated = uo?.getUpdatedDate()
result += "${u.displayName}\t${u.emailAddress}\t${u.active}\t$created\t$updated\n"
}
"<xmp>$result</xmp>"
You must be a registered user to add a comment. If you've already registered, sign in. Otherwise, register and sign in.
Tnq @Henning Tietgens sorry for that i need this information in confluence actually...how can i get that information in confluence??
You must be a registered user to add a comment. If you've already registered, sign in. Otherwise, register and sign in.
hi @Henning Tietgens can you please help me with the script for getting the list of users in Confluence., Name, Email Address, and active and in active users list and created , last updated date in a single script? is that possible to get all these details in a single script? please help me in this thank you in advance
You must be a registered user to add a comment. If you've already registered, sign in. Otherwise, register and sign in.
Hi Murthy,
try this.
import com.atlassian.crowd.embedded.api.ApplicationFactory
import com.atlassian.crowd.manager.application.ApplicationService
import com.atlassian.crowd.model.user.TimestampedUser
import com.atlassian.sal.api.component.ComponentLocator
import com.atlassian.user.UserManager
def userManager = ComponentLocator.getComponent(UserManager)
def applicationService = ComponentLocator.getComponent(ApplicationService)
def applicationFactory = ComponentLocator.getComponent(ApplicationFactory)
def application = applicationFactory.getApplication()
def result = "Name\tEmail\tActive\tCreated\tUpdated\n"
def created
def updated
userManager.getUsers().each { u ->
def modelUser = applicationService.findUserByName(application, u.name)
if (modelUser instanceof TimestampedUser) {
def timestampedUser = modelUser as TimestampedUser
created = timestampedUser.getCreatedDate()
updated = timestampedUser.getUpdatedDate()
} else {
created = null
updated = null
}
result += "${modelUser.displayName}\t${modelUser.emailAddress}\t${modelUser.isActive()}\t$created\t$updated\n"
}
"<xmp>$result</xmp>"
You must be a registered user to add a comment. If you've already registered, sign in. Otherwise, register and sign in.
Hi @Henning Tietgens tnq but it is not working for me and i have a script in Jira which gives all the details in a table
import com.atlassian.jira.component.ComponentAccessor
import com.atlassian.jira.security.login.LoginManager
import java.text.SimpleDateFormat;
import java.util.Date;
import com.atlassian.jira.user.util.UserUtil
UserUtil userUtil = ComponentAccessor.getUserUtil()
def loginManager = ComponentAccessor.getComponentOfType(LoginManager.class)
def users=ComponentAccessor.getUserUtil().getUsers()
StringBuilder builder=new StringBuilder()
builder.append("<table border = 1><tr><td><b>User Name</b></td><td><b>Full Name</b></td><td><b>eMail Address</b></td><td><b>Last Login</b></td><td><b>Status</b></td><td><b>Group</b></td></tr>")
users.each{
Long lastLoginTime = loginManager.getLoginInfo(it.username).getLastLoginTime()
String activeStatus=it.active
if(activeStatus=="false")
builder.append("<tr><td>"+it.username+"</td><td>"+it.displayName+"</td><td>"+it.emailAddress+"</td><td>Inactive User</td><td>"+it.active+"</td></tr>")
else if(lastLoginTime==null)
builder.append("<tr><td>"+it.username+"</td><td>"+it.displayName+"</td><td>"+it.emailAddress+"</td><td>Logon not found</td><td>"+it.active+"</td></tr>")
else if(userUtil.getGroupsForUser(it.getName()).size() == 0)
builder.append("<tr><td>"+it.username+"</td><td>"+it.displayName+"</td><td>"+it.emailAddress+"</td><td>No Group added</td><td>"+it.active+"</td></tr>")
else{
Date date=new Date(lastLoginTime);
SimpleDateFormat df2 = new SimpleDateFormat("dd/MM/yy hh:mm");
String dateText = df2.format(date);
builder.append("<tr><td>"+it.username+"</td><td>"+it.displayName+"</td><td>"+it.emailAddress+"</td><td>"+dateText+"</td><td>"+it.active+"</td></tr>")
}
}
builder.append("</table>")
return builder
can you please do change to work for confluence...i am trying a lot to change but unable to do so can you please do that for ...Thanks in advance
You must be a registered user to add a comment. If you've already registered, sign in. Otherwise, register and sign in.
Hi @Murthy Dusanapudi, did you run my last script in the script console of Confluence (you need Script Runner for Confluence)? If yes, what error did you get?
You must be a registered user to add a comment. If you've already registered, sign in. Otherwise, register and sign in.
Hi @Henning Tietgens i am getting those details with ur script and but they want it in a table if possible can you please do that for me ...Tnq
You must be a registered user to add a comment. If you've already registered, sign in. Otherwise, register and sign in.
Hi @Murthy Dusanapudi , you should learn/understand what you are doing... Scripting could be dangerous and simply copying scripts from web sites could lead to unwanted effects..
Nevertheless, here the script with html output and last login
import com.atlassian.confluence.security.login.LoginManager
import com.atlassian.crowd.embedded.api.ApplicationFactory
import com.atlassian.crowd.manager.application.ApplicationService
import com.atlassian.crowd.model.user.TimestampedUser
import com.atlassian.sal.api.component.ComponentLocator
import com.atlassian.user.UserManager
import groovy.xml.MarkupBuilder
import java.text.SimpleDateFormat
def userManager = ComponentLocator.getComponent(UserManager)
def applicationService = ComponentLocator.getComponent(ApplicationService)
def applicationFactory = ComponentLocator.getComponent(ApplicationFactory)
def loginManager = ComponentLocator.getComponent(LoginManager)
def application = applicationFactory.getApplication()
def df = new SimpleDateFormat("dd/MM/yy hh:mm")
def created
def updated
def lastLogin
def writer = new StringWriter()
def builder = new MarkupBuilder(writer)
builder.html() {
table(border: 1) {
tr {
td {b"User Name"}
td {b"Full Name"}
td {b"eMail Address"}
td {b"Status"}
td {b"Created"}
td {b"Updated"}
td {b"Last login"}
}
userManager.getUsers().each{u ->
def modelUser = applicationService.findUserByName(application, u.name)
def lastSuccessfulLoginDate = loginManager.getLoginInfo(u.name).lastSuccessfulLoginDate
if (lastSuccessfulLoginDate) {
lastLogin = df.format(lastSuccessfulLoginDate)
} else {
lastLogin = "not logged in"
}
if (modelUser instanceof TimestampedUser) {
def timestampedUser = modelUser as TimestampedUser
created = df.format(timestampedUser.getCreatedDate())
updated = df.format(timestampedUser.getUpdatedDate())
} else {
created = "unknown"
updated = "unknown"
}
tr {
td modelUser.name
td modelUser.displayName
td modelUser.emailAddress
td modelUser.isActive()?"Active":"Inactive"
td created
td updated
td lastLogin
}
}
}
}
return writer.toString()
You must be a registered user to add a comment. If you've already registered, sign in. Otherwise, register and sign in.
Hi @Henning Tietgens Thank you soo much it is working... and i am new to scripting now learning....and i don't have any knowledge in coding that's why i am searching here on web....will try to learn ...Thank you soo much
You must be a registered user to add a comment. If you've already registered, sign in. Otherwise, register and sign in.
Hi @Henning Tietgens can i send this table data as an email attachment to my manager using script? can you please help me in this ...Thanks in advance
You must be a registered user to add a comment. If you've already registered, sign in. Otherwise, register and sign in.
Hi @Henning Tietgens seen that you helped a lot of ppl in scripting ..i am new to script and unable solve one thang can u plz help me...
" we have 7 users in Jira-admins group so we don't want add any add any other user to that group, if any user accidentally added to that group then an email has to be sent to me or my team mate" ... can you please me to write a script for this please ..
import com.atlassian.jira.component.ComponentAccessor
def groupManager = ComponentAccessor.getGroupManager()
String groupName = "jira-administrators"
groupManager.getUsersInGroup(groupName)
using this script i am getting the list of users in admin group ..can you please help me in this. tnq
You must be a registered user to add a comment. If you've already registered, sign in. Otherwise, register and sign in.
Here is a Jira cloud addon developed by my company that allows you to search, filter and bulk delete users:
https://marketplace.atlassian.com/apps/1221764/user-management-by-toros
In addition, it allows you to search for inactive users (users who haven't login in a while) and perform some bulk operation.
You must be a registered user to add a comment. If you've already registered, sign in. Otherwise, register and sign in.
Hi,
I do not have Atlassian crowd integrated , can I still use this script ? or is there anyway to generate the list of inactive users in my jira without crowd services.
Thanks
Ramji
You must be a registered user to add a comment. If you've already registered, sign in. Otherwise, register and sign in.
The script doesn't need an explicit crowd integration, it's meant for a pure Jira installation. The CrowdService class used by the script is part of Jira.
You must be a registered user to add a comment. If you've already registered, sign in. Otherwise, register and sign in.
could you please help me , how to add an attachment to the mail?
we are using below script for sending a mail:
import com.atlassian.mail.Email
import com.atlassian.mail.server.SMTPMailServer
import com.atlassian.jira.component.ComponentAccessor
def emailSubject="test mail"
def emailBody="test mail body"
def emailAddress="yampalla.srinivasareddy@gmail.com"
SMTPMailServer mailServer=ComponentAccessor.getMailServerManager().getDefaultSMTPMailServer()
if(mailServer){
Email email=new Email(emailAddress)
email.setSubject(emailSubject)
email.setBody(emailBody)
mailServer.send(email)
}
You must be a registered user to add a comment. If you've already registered, sign in. Otherwise, register and sign in.
Try something like this
import com.atlassian.jira.component.ComponentAccessor
import com.atlassian.mail.Email
import com.atlassian.mail.MailException
import com.atlassian.mail.MailFactory
import com.atlassian.mail.queue.SingleMailQueueItem
import javax.activation.DataHandler
import javax.mail.BodyPart
import javax.mail.Multipart
import javax.mail.internet.MimeBodyPart
import javax.mail.internet.MimeMultipart
import javax.mail.util.ByteArrayDataSource
Multipart mp = new MimeMultipart("mixed")
BodyPart attPart = new MimeBodyPart()
// take care to set correct mime type for the attachment
ByteArrayDataSource attBds = new ByteArrayDataSource(data, 'text/plain; charset=utf-8')
attPart.setDataHandler(new DataHandler(attBds))
attPart.setFileName(attachmentFileName)
mp.addBodyPart(attPart)
def mailServerManager = ComponentAccessor.getMailServerManager()
def mailServer = mailServerManager.getDefaultSMTPMailServer()
if (mailServer && !MailFactory.settings.isSendingDisabled()) {
Email email = new Email(emailTo, emailCC, emailBCC)
email.setMultipart(mp)
email.setFrom(mailServer.getDefaultFrom())
email.setSubject(config.emailSubject)
email.setMimeType(config.emailMimeType)
email.setBody(config.emailBody)
try {
SingleMailQueueItem item = new SingleMailQueueItem(email)
ComponentAccessor.getMailQueue().addItem(item)
}
catch (MailException e) {
log.error("Error sending email", e)
}
} else {
log.warn("No mail server or sending disabled.")
}
You must be a registered user to add a comment. If you've already registered, sign in. Otherwise, register and sign in.
Thanks a lot for your help, it is working.
You must be a registered user to add a comment. If you've already registered, sign in. Otherwise, register and sign in.
You must be a registered user to add a comment. If you've already registered, sign in. Otherwise, register and sign in.