Micah Gideon Modell
Micah Gideon Modell

Reputation: 629

How can I get the base url in an ActionMailer?

I want to send out an email with a deep link back into my app, but I'd rather not have to hard-code the URL or else I have to switch it when I move from one environment to the next. How can I obtain the base url of a web app from within an ActionMailer? For example, I'd love to be able to have something like:

<%= base_uri %>listCreate?first=foo&second=bar

render something like the following in my testing environment:

http://localhost:30000/myApp/listCreate?first=foo&second=bar

and the following in production:

http://www.myDomain.com/myApp/listCreate?first=foo&second=bar

Upvotes: 3

Views: 4809

Answers (2)

Brenes
Brenes

Reputation: 351

You can set the default_url_options for your mailer in the controller where you have the current host for the request.

In my case, I send an email when I receive information in some lead creation form, so I have a LeadMailer. My solution was to create a before filter to set the host in the mailer.

Of course, you don't need to do it in a before filter, you could set it in your action.

My solutions looked like this:

class LeadsController < ApplicationController
  before_action :set_host, on: [:create]

  def set_host
    LeadsMailer.default_url_options = { host: request.host_with_port }
    LeadsMailer.asset_host = request.protocol + request.host_with_port
  end
end

I set the asset_host config because I wanted to use my images from the assets pipeline.

Now you can use the _url helpers as usual

<%= link_to 'something', something_url %>

Or your asset helpers

<%= image_url('logo.png')%>

Upvotes: 1

Debadatt
Debadatt

Reputation: 6015

Set the defult url option in config/environments/production.rb

config.action_mailer.default_url_options = { :host => 'your.app.com' }

and in mail template

the link should be

<%= link_to 'myapp', myapp_list_url %>

Hope this could help

You can refer the Action Mailer doc

Upvotes: 5

Related Questions