MVC Extension: Mailto





5.00/5 (1 vote)
Don't write your email in plain text when creating mailto-links
Introduction
If you don't want your Outlook filled with spam, you should be careful with mailto-links on your website. This extension will scramble your email address.
Using the Code
@Html.Mailto("mail@mailhost.com")
@Html.Mailto("mail@mailhost.com", "display name")
The Extension Method
public static MvcHtmlString Mailto(this HtmlHelper helper,
string emailAddress, string displayText = null)
{
if (string.IsNullOrEmpty(displayText))
displayText = emailAddress;
var sb = string.Format("<a href=\"{0}{1}\" title=\"{1}\">{2}</a>",
CharEncode("mailto:"), CharEncode(emailAddress), CharEncode(displayText));
return new MvcHtmlString(sb);
}
And you will need CharEncode()
function as well. Put it in a common library.
public static string CharEncode(string value)
{
var enc = Encoding.Default;
var retval = "";
for (var i = 0; i < value.Length; i++)
{
retval += "&#" + enc.GetBytes(new[]
{Convert.ToChar(value.Substring(i, 1))})[0] + ";";
}
return retval;
}