Generating a HTML Link to an Email Address

Problem

You want to add a mailto: link to your Blade template.

You want the email address to be obfuscated so that screen scrapers won't easily be able to harvest the email address.

Solution

Use the HTML::mailto() method.

The first argument to the method is the email address.

{{ HTML::mailto('a@b.c') }}

This will create the mailto link and display the email address as the link text. Notice that Laravel automatically and randomly obfuscates the address. But the address will appear correctly in browsers.

<a href="ma&#105;&#x6c;&#116;o&#58;&#97;&#64; \
  &#x62;.&#99;">&#97;&#64;&#x62;.&#99;</a>

(Note backslash above is used to continue line for smaller screens.)

If you pass a second argument, that becomes the link text.

{{ HTML::mailto('a@b.c', 'Email Me') }}

That will produce something similar to below (the actual obfuscation will vary).

<a href="m&#x61;i&#108;&#x74;&#x6f;&#x3a;&#x61; \
  &#x40;&#98;&#46;&#x63;">Email Me</a>

(Backslash above is used to continue the line for smaller screens.)

You can pass a third argument as an array of attributes to apply to the anchor tag.

{{ HTML::mailto('a@b.c', 'Email Me', array('class' => 'btn')) }}

Now the anchor has a class attribute.

<a href="&#109;&#97;&#105;&#108;&#x74;o&#x3a; \
  &#97;&#64;b.&#x63;" class="btn">Email Me</a>

Discussion

This method uses the HTML::obfuscate() method to obfuscate the email address.

See Obfuscating a String.

comments powered by Disqus