Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to set the ActionMailer default_url_options's :host dynamically to the request's hostname?

I am trying to set the :host for action mailer default url options.

I have the below set in all the environment files

config.action_mailer.default_url_options = {   :host => "localhost" } 

I want to make it more dynamic by providing the request host.

when I try to set it by

config.action_mailer.default_url_options = {   :host => request.domain } 

OR

config.action_mailer.default_url_options = {   :host => request.env["SERVER_NAME"] } 

It throws error... doesn't recognize "request" object

is there any way I can set this to the request host, not by hardcoding...?

like image 583
Madhusudhan Avatar asked Aug 08 '10 01:08

Madhusudhan


People also ask

How do I send an email to ROR?

Go to the config folder of your emails project and open environment. rb file and add the following line at the bottom of this file. It tells ActionMailer that you want to use the SMTP server. You can also set it to be :sendmail if you are using a Unix-based operating system such as Mac OS X or Linux.

How do I Preview mail in Rails?

To preview it, create a file in test/previews and call the mailer method just as you would from any model or controller in your app. Then you can preview the email at [/rails/mailers/notification/welcome](http:// rails/mailers/notification/welcome).


1 Answers

It is also possible to set a default host that will be used in all mailers by setting the :host option in the default_url_options hash

in an application_controller.rb add:

class ApplicationController < ActionController::Base   def default_url_options     { host: request.host_with_port }   end end 

Source: https://edgeguides.rubyonrails.org/action_controller_overview.html#default-url-options

Alternatively, you can pass the request when calling the mailer function from the controller

class UserMailer < ActionMailer::Base    def welcome_email(user, request)     @user = user     @url  = user_url(@user, host: request.host_with_port ) # do this for each link     mail(:to => user.email, :subject => "Welcome to My Awesome Site")   end end 

Source : https://guides.rubyonrails.org/action_mailer_basics.html#generating-urls-with-named-routes

like image 188
montrealmike Avatar answered Oct 10 '22 09:10

montrealmike