How to Construct Mailto: URLs in a Foolproof Way

Learn Where JavaScript Helps Out

Encoding mailto URLs correctly is a bit cumbersome. Fortunately, JavaScript helps out.

If you want to specify anything more than just an email address in a mailto: URL — like suggesting a default subject or even a default body — you have to use certain characters.

You can't simply hit the return key to break the line in a default body. That would make the browser choke. You have to use funny expressions like "%20" or "%A0%B0" instead.

What Are Hex Codes?

The strange compilations of characters are hex codes of ASCII characters that are required to be encoded in URLs by RFC 1738 - Uniform Resource Locators (URL).

How Do I Know What To Use?

Here's some good news: you do not need to know how to construct these hex representations. This is where the JavaScript helps out.

The JavaScript Encode URIComponent()

JavaScript knows a function called encodeURIComponent() that will encode any string it gets passed as an argument and return it for us to use. For example, encodeURIComponent("Doc, do da Dance!") produces the following:


Yes, it's that obscure. If you do this cryptography by hand, chances are you will make a mistake. JavaScript will not make a mistake (fingers crossed). And here's how to use encodeURIComponent() to ease the composition of your mailto URLs:

All we need to do is to replace any occurrence of a string in our URL with the function "encodeURIComponent()," which sees our string as an argument.


We 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:<subject>

Ehere <subject> is our 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:


Using EncodeURIComponent() With Mailto URLs

You can use encodeURIComponent() in a mailto URL. All you need to do is 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.

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

With <script language="JavaScript"> you tell it to write() something at the current position in the document; something which is composed of three parts. First, the beginning of a mailto link as we know it. Then an escaped string. And the ending tag.

More From Us