Method: ActionView::Helpers::UrlHelper#mail_to

Defined in:
actionview/lib/action_view/helpers/url_helper.rb

#mail_to(email_address, name = nil, html_options = {}, &block) ⇒ Object

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>


487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
# File 'actionview/lib/action_view/helpers/url_helper.rb', line 487

def mail_to(email_address, name = nil, html_options = {}, &block)
  html_options, name = name, nil if name.is_a?(Hash)
  html_options = (html_options || {}).stringify_keys

  extras = %w{ cc bcc body subject reply_to }.map! { |item|
    option = html_options.delete(item).presence || next
    "#{item.dasherize}=#{ERB::Util.url_encode(option)}"
  }.compact
  extras = extras.empty? ? "" : "?" + extras.join("&")

  encoded_email_address = ERB::Util.url_encode(email_address).gsub("%40", "@")
  html_options["href"] = "mailto:#{encoded_email_address}#{extras}"

  ("a", name || email_address, html_options, &block)
end