Internet, Networking, & Security Web Development How to Construct Failproof 'Mailto' URLs JavaScript protects against coding errors by Heinz Tschabitscher Writer A former freelance contributor who has reviewed hundreds of email programs and services since 1997. our editorial process Heinz Tschabitscher Updated on April 20, 2020 Web Development CSS & HTML Web Design SQL Tweet Share Email 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!") produces Doc%2C%2 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\ The result of this function call is: When%2C%20when%20is%20now%3F%20(if%20%22no Using encodeURIComponent() 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=\"mailto:recipient@example.com?subject=" + encodeURIComponent. ("When, when is now? (if \"now\" is here)") + "\">mail me!</a>")</script> Was this page helpful? Thanks for letting us know! Get the Latest Tech News Delivered Every Day Email Address Sign up There was an error. Please try again. You're in! Thanks for signing up. There was an error. Please try again. Thank you for signing up. Tell us why! Other Not enough details Hard to understand Submit