Extract email address from comment
Asked by Quang Nguyen:

Hello,

My company is moving to a Quiet Scheme where we are creating all our own notifications. I am trying to create a rule that notifies users when they are @ mentioned in a comment. We are using our own instance, not the cloud one.

So far I have the following set up:

![Capture.PNG](https://community.atlassian.com/t5/image/serverpage/image-id/279405i50A3CC981DD21E3B/image-size/large?v=v2&px=999 "Capture.PNG")

This identifies when \[\~ is in the comment body, so it triggers when a @ mention is made.

I am now trying to extract the email address from the comment body to be able to email that user, and have been unable to do so.

I have tried the following so far, copying and pasting suggestions from similar threads I found:

```
test 1 \[\~.*?\]
test 2 {{issue.comment.last.body.text("([a-zA-Z0-9_.+-]+@[a-zA-Z0-9-]+\.[a-zA-Z0-9-.]+)")}}
test 3 {{issue.comment.last.body.match("([a-zA-Z0-9_.+-]+@[a-zA-Z0-9-]+\.[a-zA-Z0-9-.]+)")}}
test 3 {{issue.comment.last.body.text.match("([a-zA-Z0-9_.+-]+@[a-zA-Z0-9-]+\.[a-zA-Z0-9-.]+)")}}
test 4 {{issue.comment.last.body.text.substringBetween("o:","]")}} 
test 5 {{issue.comment.last.body.substringBetween("o:","]")}} 
test 6 {{issue.comment.last.body.substringBetween("*: ","\n")}}
test 7 {{issue.comment.last.body.text}}
test 8 {{issue.comment.last.body.html}}
test 9 {{issue.summary.substringBetween("\[\~","\]")}}
```

All of these are returning blanks, except for Test 7 and 8 which are returning the last comment body, however I would like to extract only the email address in the comment in a format where I can put it in the "to" field to send an email.

Thank you!

Quang


Answers:
author: Darryl Lee
body: Ahhhh, [@Kalyan Sattaluri](/t5/user/viewprofilepage/user-id/5312306) and [@Bill Sheboy](/t5/user/viewprofilepage/user-id/1685313)'s discussion above made me realize there's possibly a much simpler solution.

***IF*** your JIRA usernames are the same as the first part of your company's email addresses (which is fairly common, especially if you sync with Active Directory for your accounts), then you wouldn't need a lookup.

So if Jira username is something like **quangn** and your email is **quangn@yourcompany.com**, then this regular expression should work in the To: field for sending an Automation email:

```
{{issue.comment.last.body.match("\[\~(.+?)\]").concat("@YOURCOMPANYDOMAIN.com"){{/}}
```

The rule is substantially simpler and faster, because it doesn't require an API lookup.

**Unfortunately** we are still unable to handle multiple mentions. In this case it's because Automation will apparently not accept a comma-delimited set of email addresses in the **To:** field.

Additionally, because we should handle the case of multiple mentions and at least send to the **first** mention (or as mentioned before, the **last**), we need to check for multiple recipients, and slightly adjust the regex to only grab the FIRST mention:

```
{{issue.comment.last.body.match("\[\~(.+?)\]").first.concat("@YOURCOMPANYDOMAIN.com"){{/}}
```

(NOTE: If you have the latest version of Automation for Jira (9.0.1) you could instead [create a variable](https://confluence.atlassian.com/automation/jira-automation-actions-993924834.html#create-variable) and use that in the Mail action. Due to a [migration issue](https://confluence.atlassian.com/automation/upgrading-to-automation-for-jira-7-3-or-later-1055951956.html) we haven't upgraded to that version yet.)

Anyways, the somewhat simpler rule (without a lookup) looks like this:

![Screenshot 2023-09-09 at 5.20.34 PM.png](https://community.atlassian.com/t5/image/serverpage/image-id/279695i91FE6B0B8488F285/image-size/large?v=v2&px=999 "Screenshot 2023-09-09 at 5.20.34 PM.png")

comments: author: Quang Nguyen
body: Thanks so much Darryl for this! As someone who only knows the very basics of regex, it always seems like black magic to me when someone manages to hack something together like your code.

Manually concatenating is a really clever workaround. Unfortunately my email is quang.nguyen**2** [@company](/t5/user/viewprofilepage/user-id/2789927).com, probably because I have a (relatively) common first and last name. I suspect your RegEx above would work for about 99% of emails, which is so *painfully* close, but I think actually looking up the email may be the only way to guarantee accuracy.

I've been really trying to avoid using API calls because I have never used them before, but I've seen enough answers in other threads that rely on APIs that I think I just need to bite the bullet and really go out of my comfort zone for a while. This one's for all the Nguyens and Lees and Smiths of the world.

Thank you again for putting together such thorough documentation in your other reply. I will definitely need it :)


author: Quang Nguyen
body: I am going to accept this answer for anyone in the future who works at a smaller company, where this wouldn't be as much of an issue.


author: Darryl Lee
body: Hey Quang - is your username in Jira not also **quang.nguyen2**?

By Username I mean what you see at <https://YOURJIRAINSTANCE/secure/ViewProfile.jspa>


author: Quang Nguyen
body: Hey Darryl, my username in Jira is "nguyenq"

Not everyone in my company will be using Jira. Also I think the original person with my email may have left.

![2023-09-11_16h54_29.png](https://community.atlassian.com/t5/image/serverpage/image-id/280020iC28D0BFAB98C7F3A/image-size/large?v=v2&px=999 "2023-09-11_16h54_29.png")


author: Darryl Lee
body: Aw bummer. Yeah, that makes sense.


author: Darryl Lee
body: I'm not sure how this would work, because when I type @ darryl to mention myself in a comment, it converts that to: **\[\~darryllee\]**, which is NOT an email address.

Are you saying that users have been trained (and are willing?!) to @ mention someone with @ darryl *and then also* type **darryllee@youremail.host**?

So a comment would look like:
> Hey @darryllee (darryllee@youremail.host) can you be sure to take a look at this bug?

Because that... is some kind of training. :-}

comments: author: Curt Holley
body: I agree with [@Darryl Lee](/t5/user/viewprofilepage/user-id/1365322) and will add: Why would you turn off ALL notifications (rather than curating and controlling them) and then try and reinvent the wheel with a bespoke system?


author: Quang Nguyen
body: Thanks for your suggestions.

I believe the intent is that users were complaining about getting too many email notifications, and my company was solving this by turning them all off and then recreating only the activities we want notifications for via automations. That decision has been made and the quiet scheme will roll out soon. I have been asked to help with creating these notifications.

As for the code above,

```
{{issue.comment.last.body.text}}
```

converts to "test message Nguyen Quang (CYSC)" which is my name and a code for my position.

```
{{issue.comment.last.body.html}}
```

converts to the same, except 'Nguyen Quang (CYSC)' is a link to my Jira profile page.

I am trying to convert 'Nguyen Quang (CYSC)' in either message to a usable email, to use in the To field to send an email.

We are also on the Jira Data Center, not Jira Cloud, if that helps.


author: Darryl Lee
body: Oof. I'm sorry to hear that leadership made such a poor decision.

But hey, one bad idea deserves another right? So let's get hacking!

Regex {#toc-hId--436544105}
---------------------------

Ok, so the regex you want is this:

```
{{issue.comment.last.body.match("\[\~(.+?)\]").first|issue.comment.last.body.match("\[\~(.+?)\]")}}
```

(A great resource for writing and testing regular expressions is [https://regex101.com/](https://regex101.com/r/wjRYa4/2) - that links to the regex above.)

You may be asking yourself, what's the deal with the repetition?

Well, it's because Automation's [match()](https://confluence.atlassian.com/automation074/text-functions-1141481322.html#match) operator will return a single captured group if there is only one match, but if there are more than one (say somebody mentions \[\~nguyenquang\] and \[\~darryllee\]), then it will return a ***list*** containing all the matches, so something like: **nguyenquang, darryllee**

Now, you might be thinking - that's awesome! I can mail both people!

NOPE! because we're not done yet.

You'll notice in my example that what you're matching is the **darryllee in \[\~darryllee\]** . You'll also notice that **darryllee** is not an email address.

SO! Now we have the fun task of looking up the email address for the user. But because Automation for Jira Data Center does not yet have the "Advanced branching" functionality (see [JIRAAUTOSERVER-749](https://jira.atlassian.com/browse/JIRAAUTOSERVER-749)) that would let you iterate through your list of multiple users, we only can do this lookup for the first person mentioned. Or, if you want, the last. But sadly, not all of them.

Lookup Email {#toc-hId-2050968728}
----------------------------------

OK, looking up an email address for a username. For that, you're going to have to make a call to the [REST API](https://developer.atlassian.com/cloud/jira/platform/rest/v2/api-group-users/#api-rest-api-2-user-get), and you'll be calling doing that with the "Send web request" described in [this article](https://community.atlassian.com/t5/Jira-articles/Automation-for-Jira-Send-web-request-using-Jira-REST-API/ba-p/1443828).

NOTE: In that article, they are talking about Jira CLOUD, not Data Center, so you will need to do a few things differently than it specifies:

* Here are on-prem instructions to [Set up a Personal Access Token](https://confluence.atlassian.com/enterprise/using-personal-access-tokens-1026032365.html)
* **You will not need to base64 encode your username+token**
* Your **Authorization** header will be: **Bearer \<yourToken\>**

You should then be able to follow the instructions ahead, but instead use this URL:

```
https://YOURJIRASERVER/rest/api/2/user?username={{issue.comment.last.body.match("\[\~(.+?)\]").first.urlEncode|issue.comment.last.body.match("\[\~(.+?)\]").urlEncode}}
```

Yeah, that's ugly. Oh, and unlike the example, we can't put that into a variable because Automation for Jira Data Center doesn't support them yet. (Oh wait, they just added it! See [JIRAAUTOSERVER-22.](https://jira.atlassian.com/browse/JIRAAUTOSERVER-22) Well we had some problems with that version of Automation.)

ALSO, had to add [**urlEncode**](https://confluence.atlassian.com/automation/jira-smart-values-text-fields-993924863.html#urlEncode) to the URL in case you have some non-ascii characters in your usernames.

It should look something like this:

![Screenshot 2023-09-08 at 9.56.58 PM.png](https://community.atlassian.com/t5/image/serverpage/image-id/279658i065144F0A3A0CBF4/image-size/large?v=v2&px=999 "Screenshot 2023-09-08 at 9.56.58 PM.png")

So yeah, after you make that Web Request, it returns the response in {{webhookResponse}} and you can get the email out of that via {{webhookResponse.body.emailAddress}}.

The final rule {#toc-hId-243514265}
-----------------------------------

Anyways, the end product should look something like this: (Oh yeah, I use an IF at the beginning to make sure the Comment has a mention in it at all.)

![Screenshot 2023-09-08 at 9.56.49 PM.png](https://community.atlassian.com/t5/image/serverpage/image-id/279657iA61A3E19D31D7583/image-size/large?v=v2&px=999 "Screenshot 2023-09-08 at 9.56.49 PM.png")

Whew. That's kind of ugly. But there you have it!


author: Quang Nguyen
body: Hi, I did try this but I am getting an error:

![2023-09-11_15h24_18.png](https://community.atlassian.com/t5/image/serverpage/image-id/280019i704A9D8B2BF98BE5/image-size/large?v=v2&px=999 "2023-09-11_15h24_18.png")

I did notice in the Send Web Request article you linked, the HTTP method used was POST, whereas your steps used GET. I did try both and got that error each time. I did not encode anything.

Appreciate all the help!


author: Darryl Lee
body: GAH, I had a typo in the URL (last parentheses was in the wrong place). I've fixed it above, and here it is, corrected:

```
https://YOURJIRASERVER/rest/api/2/user?username={{issue.comment.last.body.match("\[\~(.+?)\]").first.urlEncode|issue.comment.last.body.match("\[\~(.+?)\]").urlEncode}}
```

Sorry about that. I added **urlEncode** late in the process.


author: Quang Nguyen
body: Thanks for the speedy reply!

The rule is now publishing successfully. However the notification email is not being sent and I am getting this error in the rule's audit log:
> Error publishing webhook. Response HTTP status:  
401  
> **Error response HTTP body:**  
\<?xml version="1.0" encoding="UTF-8" standalone="yes"?\>\<status\>\<status-code\>401\</status-code\>\<message\>Client must be authenticated to access this resource.\</message\>\</status\>  
I've tried clearing my cache and cookies, and this still happens. I am an admin on the board I am testing this on.


author: Darryl Lee
body: Hey yeah, no, that's definitely a problem with the Authentication token.

You followed these steps:

* [Set up a Personal Access Token](https://confluence.atlassian.com/enterprise/using-personal-access-tokens-1026032365.html)
* Your **Authorization** header will be: **Bearer \<yourToken\>**
* Reminder, you DO NOT need to base64 encode your **username:token**. That is only on Cloud.

I would delete the old token, regenerate a new one, and very carefully copy/paste it into the Headers (and don't close that window with the token until you've confirmed it works):
> Authorization: Bearer JUSTYOURTOKEN

(You do not enter a colon on the site. And you need to make sure there's not any extra spaces before/after.)


author: Quang Nguyen
body: Oops, I was trying to create a token through <https://id.atlassian.com/manage-profile/security/api-tokens> before, which has a much longer token.

I did go through your Personal Access Token link, and generated a PAT which is a much smaller string. My token is about 45 characters.

It is still failing with the same error code, 401, when I tried it with the other token though. I've tried copying it manually, copying it using the clipboard button when creating a token, and manually checking all the spaces before and after.

Here is my setup, not much has changed:

![2023-09-11_19h03_40.png](https://community.atlassian.com/t5/image/serverpage/image-id/280025i11EB9ECB677830D5/image-size/large?v=v2&px=999 "2023-09-11_19h03_40.png")

And here is the audit log:

![2023-09-11_19h06_28.png](https://community.atlassian.com/t5/image/serverpage/image-id/280027iF1C5ABB7DBB283FC/image-size/large?v=v2&px=999 "2023-09-11_19h06_28.png")

Thanks for hanging through this with me!


author: Darryl Lee
body: I think see the problem now. For the Header name you wrote:

**Authorize**

It should be:

**Authorization**

Give that a try!


author: Quang Nguyen
body: That **worked** ! What a simple mistake on my end. Thank you **so much** for helping me through all of this.

It feels a bit silly to have to go through all these hoops to message someone who is mentioned, but I suppose I am trying to do something a bit silly in the first place. Regardless, thank you so much for personalizing the documentation to my situation and helping me troubleshoot through completion. You are amazing, and I really really appreciate it! Now I have a (very fledgling) skill in my repertoire :)


author: Darryl Lee
body: Glad we got it working!


author: Quang Nguyen
body: Hi [@Darryl Lee](/t5/user/viewprofilepage/user-id/1365322)

Me again, with a related question.

I have another rule set up to fire if any comment is made at all:![Capture.PNG](https://community.atlassian.com/t5/image/serverpage/image-id/281293i7FAA6949AC1E0362/image-size/large?v=v2&px=999 "Capture.PNG")

This rule is for general comments, to notify the assignee when a comment is made on a task.

When a user is @ mentioned, it is firing both this general comment rule and the @mention rule we set up above. I would like to make it so that only one of these fires (ideally only the @mention rule). **How would I make sure only one rule fires?**

Failed solutions I tried:

I have tried adding the condition that was originally used to detect that a comment was made, but this did not work:

![Capture.PNG](https://community.atlassian.com/t5/image/serverpage/image-id/281295i0D7F3E5757CFCB0A/image-size/large?v=v2&px=999 "Capture.PNG")

I've also tried "contains regular expression" for a few negative lookaheads I found. The thought was the negative lookahead would fail when it detects a comment, so the condition would return False and not trigger the email. That also did not work, but I suspect that's primarily because I did not set the regex up correctly.

I also tried looking up ways to, when one rule triggers, force it to stop other rules from triggering as well, but could not find a solution.


author: Darryl Lee
body: So let me see if I'm understanding:

* You want a rule that notifies the Assignee of new comments IF
  * the commentor is NOT the assignee
  * AND the comment does NOT contain a mention?

So it would seem like you need to have multiple conditions. I tested this and it seemed to work. Also, I removed some things that I thought were not necessary (also it's safer to try to match initiator and assignee based on usernames instead of displayNames, since as we know, there can be multiple people with the same name).

And you really shouldn't use regular expressions if you don't have to.

![Screenshot 2023-09-18 at 2.31.22 PM.png](https://community.atlassian.com/t5/image/serverpage/image-id/281325iD8BB0D4684383E7C/image-size/large?v=v2&px=999 "Screenshot 2023-09-18 at 2.31.22 PM.png")

If things don't work, it's always helpful to add some Audit Logging to see what's going on:

![Screenshot 2023-09-18 at 2.33.51 PM.png](https://community.atlassian.com/t5/image/serverpage/image-id/281326i6609237E162BFEEA/image-size/large?v=v2&px=999 "Screenshot 2023-09-18 at 2.33.51 PM.png")


author: Quang Nguyen
body: Thanks so much! Currently, when the assignee is @ mentioned in an issue, they would be sent an email that an issue they were assigned to was mentioned on, and that they were @ mentioned. I wanted to create rules that:

* Sends them the email that they were @ mentioned
* Did *not*send them the email saying the issue they were assigned to was commented on, since this was redundant.

I managed to do that by adding

```
{{issue.comments.last.body}} does not contain {{issue.assignee}}
```

and testing using the audit log trick you showed me. I did not know log messages could be added that way. This is going to help me troubleshoot things much easier in the future, thank you!


author: Kalyan Sattaluri
body: Below regex extracts email address from last comment but its returns it twice because email address is hyper linked (?).. Maybe you can see if you can customize this?

{{issue.comments.last.body.match("(\[a-zA-Z0-9_.+-\]+@\[a-zA-Z0-9-\]+\\.\[a-zA-Z0-9-.\]+)")}}

comments: author: Bill Sheboy
body: Hi [@Kalyan Sattaluri](/t5/user/viewprofilepage/user-id/5312306) -- Welcome to the Atlassian Community!

Once you have two results for the email address, you could convert that value to a list, and then grab the first one with either .first or .get(0) added to the end of the expression.

However, that only works for linked email address values. If the source is instead a mention, it must be looked up as [@Darryl Lee](/t5/user/viewprofilepage/user-id/1365322) suggests.

Kind regards,  
Bill


author: Quang Nguyen
body: {deleted}