Click here to Skip to main content
65,938 articles
CodeProject is changing. Read more.
Articles
(untagged)

MVC Extension: Mailto

0.00/5 (No votes)
12 Jul 2012 2  
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;
}

License

This article has no explicit license attached to it but may contain usage terms in the article text or the download files themselves. If in doubt please contact the author via the discussion board below.

A list of licenses authors might use can be found here