How to Construct Failproof 'Mailto' URLs

JavaScript protects against coding errors

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 content we describe below uses JavaScript, which has a higher technical component than other solutions. We recommend constructing normal mailto links to obtain those links in the easiest way possible.

Degui Adil / EyeEm / Getty Images

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!")

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 with a subject of "When, when is now? (if "now" is here)." The URL will look like this:

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\

The result of this function call is:


Using e​ncodeURIComponent() With Mailto: URLs

To use encodeURIComponent() in a mailto URL, compose the whole link (from "<a href=..." to "</a>") within the document.write() JavaScript function, 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=\""
+ encodeURIComponent. ("When, when is now? (if \"now\" is here)")

+ "\">mail me!</a>")

Was this page helpful?