Convert Emails to MailTo Links

The following PeopleCode function finds email addresses (using a regular expression) and encloses them in a anchor hyperlink tag with a mail to link.

So for example the text: is replaced with the HTML:

<a href=""></a>

This is the PeopleCode function:

Constant &DOMAIN = "";
Function ConvertEmailToLinks(&sInput As string) Returns string;
   Local JavaObject &jEmailRegex, &jEmailLinkRegex, &jInput;
   Local string &sHTML;
   &jEmailRegex = CreateJavaObject("java.lang.String", "[\w-.]+@(\w+.|)" | &DOMAIN);
   /* Replace the found match ($0 back reference) and enclose with a href mailto HTML tag */
   &jEmailLinkRegex = CreateJavaObject("java.lang.String", "<a href=""mailto:$0"">$0</a>");
   /* Store the text to be scanned for email addresses as a Java string object */
   &jInput = CreateJavaObject("java.lang.String", &sInput);
   /* Perform a replace all using the search email regex and the email link regex */
   &sHTML = &jInput.replaceAll(&jEmailRegex, &jEmailLinkRegex);
   Return &sHTML;
NOTE: Remember to replace the constant, &DOMAIN with your organisation's base domain. The search regex in this example may need changing to cater for more specific email formats.

There are three key parts to this code.

The first part is the regular expression stored in the Java object &jEmailRegex which is converted to:


This matches any email address that ends with your base domain (, or has one subdomain in it ( and is preceded by a word that can include a full stop or a hyphen in it (e.g. or

Underscores are automatically catered for by the \w word match expression.

You cam voew this regex in action using RegExr. Adjust and test to ensure it matches the email address format used in your organisation.


NOTE: the last example with the asterisk character which only does a partial match.

The second key part of this code is the Java object &jEmailLinkRegex. This regex is what performs the conversion to a hyperlink:

<a href="mailto:$0">$0</a>

The $0 in this code is a back reference and evaluates to the result of the search regex (&jEmailRegex). So it is replaced by the email address found.

The third key part is the call to the replaceAll method. This is what causes all matching email addresses to be converted, taking the search regex (&jEmailRegex) and replacing it with the link regex (&jEmailLinkRegex).

No Comments
Back to top