How do I properly encode a mailto link?
Asked Answered
T

1

10

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)));
Trifolium answered 26/9, 2011 at 20:53 Comment(2)
Your first version is almost correct, except you should unencode the &s. You are assigning it to the Text property. It should take care of the HTML encoding internally. The only thing you need to worry about is it being a valid URI.Rejuvenate
@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?Trifolium
O
9

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

Opiate answered 26/9, 2011 at 20:54 Comment(4)
I tried.. is the 2nd version of the code in my question what you had in mind?Trifolium
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 urlHardtop
@Yuck — It is really an answer. The second sentence describes exactly what needs to be done.Opiate
@ScottStafford — Just seen the comment (2.5 years later), "yes".Opiate

© 2022 - 2024 — McMap. All rights reserved.