How do I properly encode a mailto link?

10,719

You are putting some content in a URL, then representing that URL in HTML. So URLEncode it then HTMLEncode what you get from URLEncode.

Share:
10,719

Related videos on Youtube

Scott Stafford
Author by

Scott Stafford

I want what everybody wants. A job where I can change the world modestly for the better, that makes me enough money so I can have everything I want and not so much that my kids want to kill me for the inheritance, and that gives me enough fame to stroke my ego yet I can still dine out in peace.

Updated on June 04, 2022

Comments

  • Scott Stafford
    Scott Stafford almost 2 years

    I am generating some HTML and I want to generate an XSS- and database-content-safe mailto link. What is the proper encoding to use here? How's this?

    myLiteral.Text = string.Format(
      "mailto:{0}?Content-Type=text/html&Subject={1}&body={2}", 
      HttpUtility.UrlEncode(email_address),
      HttpUtility.UrlEncode(subject),
      HttpUtility.UrlEncode(body_message));
    

    Should I use UrlEncode here? HtmlEncode? Do what I did, then HtmlEncode the entirety? I'm writing HTML of a URL, so I'm a little unclear...

    @Quentin, is this what you're describing? (Changed &s to & since I'm about to HtmlEncode...)

    myLiteral.Text = 
      HttpUtility.HtmlEncode(HttpUtility.UrlEncode(
        string.Format(
          "mailto:{0}?Content-Type=text/html&Subject={1}&body={2}", 
          email_address, subject, body_message)));
    
    • Scott Stafford
      Scott Stafford over 12 years
      @liho1eye: I think that's only true for an ASP Literal if myLiteral.Mode == Encode, which is not the default. But the second version should have the effect you were going for, yes?
  • Scott Stafford
    Scott Stafford over 12 years
    I tried.. is the 2nd version of the code in my question what you had in mind?
  • Erlend
    Erlend over 12 years
    I would go with the first one. Or a mix of the two. Htmlattributeencoding the whole value, and url encoding the values inserted into the url
  • Quentin
    Quentin almost 10 years
    @Yuck — It is really an answer. The second sentence describes exactly what needs to be done.
  • Quentin
    Quentin almost 10 years
    @ScottStafford — Just seen the comment (2.5 years later), "yes".