Click here to Skip to main content
15,890,512 members
Articles / Programming Languages / C#
Tip/Trick

MVC Extension: Mailto

Rate me:
Please Sign up or sign in to vote.
5.00/5 (1 vote)
12 Jul 2012CPOL 35.8K   4  
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

C#
@Html.Mailto("mail@mailhost.com")
C#
@Html.Mailto("mail@mailhost.com", "display name")   

The Extension Method

C#
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.

C#
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, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)


Written By
Software Developer (Senior) Aurum AS
Norway Norway
Microsoft Certified Solutions Developer (MCSD)

Personal website:
stian.net

My projects:
CRM1.no - A free to use norwegian crm software
Fakturax - A free to use norwegian invoice software
Timeføring.no - A free to use norwegian timereg software
MittUtlegg - A free to use norwegian software for receipts
SupportWeb - A free to use norwegian software customersupport

Comments and Discussions

 
-- There are no messages in this forum --