'Safely URL escape emails with string templates in Kotlin

I have some Kotlin code that is sending email addresses that are URL query encoded, so certain characters must be escaped. However there are errors because some valid email addresses contain "$" or "${expression}". For example:

import java.net.URLEncoder

fun main() {
    val encodedEmail = URLEncoder.encode("bademail_${2*4}@gmail.com", Charsets.UTF_8)
    println(encodedEmail)
}

returns:

bademail_8%40gmail.com

When I need it to return:

bademail_%24%7B2*4%7D%40gmail.com

Note that these email addresses are coming from an external source so I cannot just manually change the email address by adding an escape character like so:

val escapedTemplateEmail = "bademail_\${2*4}@gmail.com"
// we are stuck with this
val troublesomeEmail = "bademail_${2*4}@gmail.com"


Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source