Click here to Skip to main content
Click here to Skip to main content

Tagged as

MVC Extension: Mailto

, 12 Jul 2012 CPOL
Rate this:
Please Sign up or sign in to 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;
}

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)

Share

About the Author

StianSandberg
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
Follow on   Twitter   LinkedIn

Comments and Discussions

 
-- There are no messages in this forum --
| Advertise | Privacy | Terms of Use | Mobile
Web03 | 2.8.141220.1 | Last Updated 12 Jul 2012
Article Copyright 2012 by StianSandberg
Everything else Copyright © CodeProject, 1999-2014
Layout: fixed | fluid