I am new to Rails and struggling with how to implement dynamic values in my mailer.
The below code all works fine apart from the reply_to which I want a dynamic value but I don't know how to do this.
The params @name, @email, @message are captured on a form and I want the reply_to values to be the same as the params passed from @email.
So, essentially the point of this is someone can book an event and then it will email their details to the event manager who can then just press "reply" and it will reply back to the email the user filled out on the form.
class BookingMailer < ActionMailer::Base
default from: "notifications@example.com"
default reply_to: @email
def contact_mailer(name,email,message)
@name = name
@email = email
@message = message
mail(to: 'info@example.com', subject: 'Event Booking', reply_to: @email)
end
end
I looked on the API docs but they seem to reference users in a database when using dynamic values.
Any help is much appreciated, thanks!
You only set a default value if you wanted to use something for methods that DON'T have an option set (for example, you've set a default from:
, so you don't need to set mail(from: "notifications@example.com"...)
each time, it'll use the default if not set).
Providing your controller is passing the email address as the second argument then your code should work, although usually I'd pass a booking:
class BookingController < ApplicationController
def create
@booking = Booking.new(safe_params)
if @booking.save
BookingMailer.contact_mailer(@booking).deliver
else
# alarums!
end
end
end
Then extract the info you want from that in your mailer:
class BookingMailer < ActionMailer::Base
default from: 'blah@blah.com'
def contact_mailer(booking)
@booking = booking
mail(to: 'info@example.com', subject: 'Event booking', reply_to: @booking.email)
end
end
Ideally you should remove the line default reply_to: @email
as it's trying to use a class level instance variable @email
, instead of the instance variable @email
that you intended. For examples on the differences between class variables, instance variables and class instance variables, see here: http://www.railstips.org/blog/archives/2006/11/18/class-and-instance-variables-in-ruby/