instance method mail_to

Ruby on Rails 8.1.2

Since v2.2.3

Available in: v2.2.3 v2.3.18 v3.0.20 v3.1.12 v3.2.22.5 v4.0.13 v4.1.16 v4.2.9 v5.2.8.1 v6.0.6 v6.1.7.10 v7.0.10 v7.1.6 v7.2.3 v8.0.4 v8.1.2

Signature

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

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 "me@domain.com"
# => <a href="mailto:me@domain.com">me@domain.com</a>

mail_to "me@domain.com", "My email"
# => <a href="mailto:me@domain.com">My email</a>

mail_to "me@domain.com", cc: "ccaddress@domain.com",
         subject: "This is an example email"
# => <a href="mailto:me@domain.com?cc=ccaddress@domain.com&subject=This%20is%20an%20example%20email">me@domain.com</a>

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

<%= mail_to "me@domain.com" do %>
  <strong>Email me:</strong> <span>me@domain.com</span>
<% end %>
# => <a href="mailto:me@domain.com">
       <strong>Email me:</strong> <span>me@domain.com</span>
     </a>

Parameters

email_address req
name opt = nil
html_options opt = {}
block block
Source
# File actionview/lib/action_view/helpers/url_helper.rb, line 488
      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}"

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

Defined in actionview/lib/action_view/helpers/url_helper.rb line 488 · View on GitHub · Improve this page · Find usages on GitHub

Defined in ActionView::Helpers::UrlHelper

Type at least 2 characters to search.

↑↓ navigate · open · esc close