I'm trying to generate a form so visitors can send an email to a fixed address without cluttering the database. When I test the form, rails returns this error...
Net::SMTPAuthenticationError in ContactsController#create
It appears the answer is to allow access to gmail for less secure apps. How can I retain the functionality without lowering security?
controllers/contacts_controller.rb
class ContactsController < ApplicationController
def new
@contact = Contact.new
end
def create
@contact = Contact.new(params[:contact])
if @contact.valid?
ContactMailer.contact_submit(@contact).deliver
flash[:notice] = "Thank you for your email, I'll respond shortly"
redirect_to new_contact_path
else
render :new
end
end
end
mailers/contact_mailer.rb
class ContactMailer < ActionMailer::Base
default to: "#{ENV['GMAIL_USERNAME']}@gmail.com"
def contact_submit(msg)
@msg = msg
mail(from: @msg.email, name: @msg.name, message: @msg.message)
end
end
models/contact.rb
class Contact
include ActiveModel::Validations
include ActiveModel::Conversion
extend ActiveModel::Naming
attr_accessor :name, :email, :message
validates_format_of :email, :with => /\A([\w\.%\+\-]+)@([\w\-]+\.)+([\w]{2,})\z/i
validates_presence_of :message
validates_presence_of :name
def initialize(attributes = {})
attributes.each do |name, value|
send("#{name}=", value)
end
end
def persisted?
false
end
end
config/environments/development.rb
config.action_mailer.default_url_options = { host: 'localhost', port: 3000 }
config.action_mailer.delivery_method = :smtp
config.action_mailer.perform_deliveries = true
config.action_mailer.default :charset => 'utf-8'
config.action_mailer.smtp_settings = {
address: 'smtp.gmail.com',
port: 587,
domain: 'localhost:3000',
user_name: ENV['GMAIL_USERNAME'],
password: ENV['GMAIL_PASSWORD'],
authentication: 'plain',
enable_starttls_auto: true
}
config/environments/production.rb
config.action_mailer.default_url_options = { host: ENV['WEBSITE'] }
config.action_mailer.delivery_method = :smtp
config.action_mailer.smtp_settings = {
address: 'smtp.gmail.com',
port: 587,
domain: ENV['WEBSITE'],
user_name: ENV['GMAIL_USERNAME'],
password: ENV['GMAIL_PASSWORD'],
authentication: 'plain',
enable_starttls_auto: true
}