method

mail_to

rails latest stable - Class: ActionView::Helpers::UrlHelper
mail_to(email_address, name = nil, html_options = {}, &block)
public

Creates a mailto link tag to the specified email_address, which is also used as the name of the link unless name is specified. Additional HTML attributes for the link can be passed in html_options.

mail_to has several methods for customizing the email itself by passing special keys to html_options.

Options

  • :subject - Preset the subject line of the email.

  • :body - Preset the body of the email.

  • :cc - Carbon Copy additional recipients on the email.

  • :bcc - Blind Carbon Copy additional recipients on the email.

  • :reply_to - Preset the Reply-To field of the email.

Obfuscation

Prior to Rails 4.0, mail_to provided options for encoding the address in order to hinder email harvesters. To take advantage of these options, install the actionview-encoded_mail_to gem.

Examples

mail_to "[email protected]"
# => <a href="mailto:[email protected]">[email protected]</a>

mail_to "[email protected]", "My email"
# => <a href="mailto:[email protected]">My email</a>

mail_to "[email protected]", cc: "[email protected]",
         subject: "This is an example email"
# => <a href="mailto:[email protected][email protected]&subject=This%20is%20an%20example%20email">[email protected]</a>

You can use a block as well if your link target is hard to fit into the name parameter. ERB example:

<%= mail_to "[email protected]" do %>
  <strong>Email me:</strong> <span>[email protected]</span>
<% end %>
# => <a href="mailto:[email protected]">
       <strong>Email me:</strong> <span>[email protected]</span>
     </a>

2Notes

Javascript encoding DOES work!

Bounga · Jan 20, 20095 thanks

grosser assertion is false :

mail_to('[email protected]', nil, :encode => :javascript)
# => "<script type=\\"text/javascript\\">eval(unescape('%64%6f%63%75%6d%65%6e%74%2e%77%72%69%74%65%28%27%3c%61%20%68%72%65%66%3d%22%6d%61%69%6c%74%6f%3a%78%78%78%40%78%78%78%2e%63%6f%6d%22%3e%78%78%78%40%78%78%78%2e%63%6f%6d%3c%2f%61%3e%27%29%3b'))</script>"

Use "nil" as the second parameter to tell mail_to that you want to use the first parameter for both text and email link

email_to('xxx@xxx','xxx@xxx',:encode=>'javascript') does NOT work

grosser · Aug 1, 20082 thanks

as i always want the email in the link text, email_to does not help me...

so here comes the rescue!

#http://unixmonkey.net/?p=20
# Takes in an email address and (optionally) anchor text,
# its purpose is to obfuscate email addresses so spiders and
# spammers can't harvest them.
def js_antispam_email_link(email, linktext=email)
user, domain = email.split('@')
# if linktext wasn't specified, throw email address builder into js document.write statement
linktext = "'+'#{user}'+'@'+'#{domain}'+'" if linktext == email 
out =  "<noscript>#{linktext} #{user}(ät)#{domain}</noscript>\

" out += "
" return out end