Easy C# Email Encoding (obfuscation for Mailto: links)

A simple method to HtmlEncode everything in an email address so it can be used for a "Mailto:" Href link that works, but which is useless to spam mail address harvesters. The nice thing about this is that the method can be included in Forum code, or even in a Server Control.

A simple method to HtmlEncode everything in an email address so it can be used for a "Mailto:" Href link that works, but which is useless to spam mail address harvesters. The nice thing about this is that the method can be included in Forum code, or even in a Server Control.


Following is the code for an entire script-only page that includes the method and a demo of it. Save this page as "EmailEncoder.aspx" and request it in your browser. You will see an email link that works fine. However if you View Source on the resulting page, it's all HTML Entities.

<script language="C#" runat="server">
private void Page_Load(object sender , System.EventArgs e)
{
string address="daddeo@mydomain.com";
string stuff =HtmlEncode(address);
Response.Write("<a href=mailto:"+ stuff + ">" + address+"</a>" );
}
public string HtmlEncode(string text)
{
string tempHTMLEncode = null;
int i = 0;
int acode = 0;
string repl = "";
tempHTMLEncode = text;
for (i = tempHTMLEncode.Length; i >= 1; i--)
{
acode = System.Convert.ToInt32(tempHTMLEncode[i - 1]);
if (acode == 32)
{
repl = "Â ";
}
else if (acode == 34)
{
repl = """;
}
else if (acode == 38)
{
repl = "&";
}
else if (acode == 60)
{
repl = "<";
}
else if (acode == 62)
{
repl = ">";
}
else if (acode >= 32 && acode <= 127)
{
repl = "&#" + System.Convert.ToString(acode) + ";";
}
else
{
repl = "&#" + System.Convert.ToString(acode) + ";";
}
if (repl.Length >0)
{
tempHTMLEncode = tempHTMLEncode.Substring(0, i - 1) +
repl + tempHTMLEncode.Substring(i);
repl = "";
}
}
return tempHTMLEncode;
}
</script>

By Peter Bromberg   Popularity  (2672 Views)