How to Construct Failproof Mailto: URLs

Learn Where JavaScript Helps Out

Encoding mailto: URLs correctly is a bit cumbersome. This is especially true when you need to include a subject line, default message, or other elements. Rather than simple words, you must use hex codes, which represent ASCII characters that are encoded per RFC 1738—Uniform Resource Locators (URL) standards. You don't need to remember or construct these hex representations off the top of your head, though: JavaScript can do it for you.

The JavaScript encodeURIComponent() Function

The JavaScript encodeURIComponent() function encodes any string it gets passed as an argument and returns it for use. For example, encodeURIComponent("Doc, do da Dance!") produces Doc%2C%20do%20da%20Dance!.

Yes, it's that obscure. If you do this cryptography by hand, chances are you will make a mistake—but JavaScript will not. To use encodeURIComponent() to ease the composition of your mailto: URLs, just replace any occurrence of a string in the URL with the encodeURIComponent() function, which sees our string as an argument.

For example, say you want to create a mailto: URL that initiates a message to recipient@example.com with a subject of "When, when is now? (if "now" is here)." The URL will look like this:

mailto:recipient@example.com?subject=<subject>

The subject is the string, "When, when is now? (if "now" is here)." The string as an argument to encodeURIComponent() makes the following:

encodeURIComponent("When, when is now? (if \"now\" is here)").

The result of this function call is:

When%2C%20when%20is%20now%3F%20(if%20%22now%22%20is%20here)

Using e​ncodeURIComponent() With Mailto: URLs

To use encodeURIComponent() in a mailto: URL, compose the whole link (from "<a href=..." to "</a>") within the JavaScript function document.write(), which will write any text to the document, just as if we had typed it in the HTML source.

For example:

<script language="JavaScript"><document.write("<a href=\"mailto:recipient@example.com?subject=" + encodeURIComponent. ("When, when is now? (if \"now\" is here)") + "\">mail me!</a>")</script>

With <script language="JavaScript">, you tell your email program to write() something at the current position in the document, which is composed of three parts: the beginning of a mailto: link as we know it, then an escape string, followed by the ending tag.

Was this page helpful?