How to Construct Failproof 'Mailto' URLs

JavaScript protects against coding errors

What to Know

  • 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!
  • To ease the composition of your mailto: URLs, replace any occurrence of a string in the URL with the encodeURIComponent() function.

This article explains how to use JavaScript to create "mailto" URLs. Using JavaScript, you don't have to remember or construct hex codes.

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!

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=

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 "HTML source.

For example:



Was this page helpful?