How to correctly encode MailTo links in ASP.NET MVC?

Miguel Moura picture Miguel Moura · Dec 21, 2013 · Viewed 7k times · Source

I have the following mailto link on an ASP.NET MVC 5 application:

<a rel="nofollow" href="@(
  String.Format("mailto:?subject={0}&amp;body={1}", 
    "The title", "The description" + "%0D%0A" + "http://theurl.xyz")">
  share by email
</a>

This is not validating on HTML Validator. I get the error:

Bad value mailto:?subject=The subject&body=This is the url:%0D%0Ahttp://localhost:8580/home for attribute href on element a: Whitespace in query component. Use %20 in place of spaces.

I tried encoding using HttpUtility.UrlEncode but when I open the email I get "+" signs and others in the subject and body and I am not able to solve that.

Answer

Joe Krill picture Joe Krill · Mar 25, 2015

I know this is a little old, but I came across this when I was trying to figure out the best way to encode mailto links. I've found the best way is use Uri.EscapeDataString for each parameter and then encode the entire attribute thing using HttpUtility.HtmlAttributeEncode:

HttpUtility.HtmlAttributeEncode(
    String.Format("mailto:?subject={0}&body={1}", 
        Uri.EscapeDataString(subject), 
        Uri.EscapeDataString(body)))

HttpUtility.UrlEncode and HttpUtility.UrlEncodeUnicode do not correctly encode spaces -- they become plus signs ("+") which then show up as plus signs in the subject line/body/etc. HttpUtility.UrlPathEncode seems to fix that problem, but doesn't properly encode other characters like ?, #, and /. Uri.EscapedDataString seems to be the only method that properly encodes all of these characters. I imagine Uri.HexEscape would work equally as well, but it seems like that might be overkill.

Caveat: I haven't tested this with even a remotely wide variety of browsers and email clients