I'm trying to use the MailForm gem to set up a simple email form, but its not working and not even giving me any messages.
here's my controller methods
class ContactsController < ApplicationController
def new
@contact = Contact.new
end
def create
@contact = Contact.new(params[:contact])
@contact.request = request
if @contact.deliver
flash.now[:notice] = "Thanks! I'll contact you soon."
else
flash.now[:error] = 'Cannot send message.'
render :new
end
end
private
def contact_params
params.require(:contact).permit(:from_email, :from_name, :subject, :message)
end
end
and then the view (Which is actually in the profiles/show
page instead of the contact/new
page. Is that the issue?
<%= form_for @contact do |f| %>
<div class="form-group">
<%= f.label "Your Email" %>
<%= f.text_field :from_email, class: "form-control" %>
</div>
<div class="form-group">
<%= f.label "Subject" %>
<%= f.text_field :subject, class: "form-control" %>
</div>
<div class="form-group">
<%= f.label "Message" %>
<%= f.text_area :message, class: "form-control" %>
</div>
<div class="form-group">
<%= f.hidden_field :to_email, value: @user.email %>
<%= f.submit "Contact", class: 'btn btn-primary form-control' %>
</div>
<% end %>
I also think it could be a configuration issue. Here's the config I'm using for gmail
config.action_mailer.default_url_options = { host: 'localhost', port: 3000 }
config.action_mailer.delivery_method = :smtp
config.action_mailer.smtp_settings = {
address: 'smtp.gmail.com',
port: 587,
domain: 'gmail.com',
user_name: '<email>',
password: '<password>',
authentication: 'plain',
enable_starttls_auto: true }
And here's the model
class Contact < MailForm::Base
# belongs_to :user
attribute :to_email
attribute :name, :validate => true
attribute :from_email, :validate => /\A([\w\.%\+\-]+)@([\w\-]+\.)+([\w]{2,})\z/i
attribute :subject
attribute :message
def headers
{
subject: subject,
to: to_email,
from: <email>
}
end
end
I've tried just about every answer I can find on stack overflow, but nothing's working. What am I doing wrong here?
I think you forgot to permit to_email
in contact_params
def contact_params
params.require(:contact).permit(:from_email, :from_name, :subject, :message, :to_email)
end