How to generate urls for ActionMailer emails

November 13th, 2007
This is a little bit tricky, but I've found an solution in the comments from other article on this problem. First we need to set default_url_options for ActionMailer::Base. This can be done with before_filter method in ApplicationController

1
2
3
4
5
6
7
8
class ApplicationController < ActionController::Base
  before_filter :set_default_url_options_for_mailers

  def set_default_url_options_for_mailers
    ActionMailer::Base.default_url_options[:host] = request.host_with_port
  end

end
Now we can generate the url in the mailer model
1
2
3
4
5
6
7
8
9
  def email_confirmation(user)
    recipients user.email
    from  "example.com  <no-reply@example.com>"
    subject "Confirm your email address"
    content_type "text/html"

    body :user => user, :activation_page => url_for(:controller => "main", :action => 
    'activate', :only_path => false)
  end



1 Response to “How to generate urls for ActionMailer emails”

  1. Martin Says:
    Thank you! I have looked at so many pages claiming to solve this problem but yours is the only one to show the whole code fragment. My code is now working thanks to you. Martin

Leave a Reply