Search code examples
ruby-on-railsemailgmailescapingactionmailer

Rails escape things that can be auto linked by email client (Gmail, Outlook)


When you're sending emails on rails, you often use <%= variable %> to inject data in the view.

Problem is, if the variable contains something like http://google.com, email clients will happily auto create a link for that string, even though you didn't wrap it around an <a> tag. That can lead to various security problems.

Now I don't want to try to find a solution for each case. So is there a simple trick that I can use on ActionMailer views to make sure that any potential url will not be autolinked by email clients?


Solution

  • I don't think there's a easy way like a setting to prevent that, since it's happening on the client side.

    A way of deceiving the email clients is by adding <span>s in the middle of URLs, which prevents links to be added without changing the text style.

    You can do that in specific places with a helper like:

    module MailHelper
      def escape_links(text)
        h(text).gsub(/[\.:]/, '<span>\0</span>').html_safe
      end
    end
    

    And then use it in the view templates as <%= escape_links variable %>.

    I agree it'd be a bit annoying having to add this everywhere, and it seems you want a more generic solution. In that case, something that might work (I didn't try it myself yet) is to apply similar approach using email interceptors to change the message body. You would need a smarter replacement strategy though to avoid adding <span>s inside <a>'s hrefs.