I am going through this tutorial (link:https://www.murdo.ch/blog/build-a-contact-form-with-ruby-on-rails-part-1) to create a simple contact us form on my existing rails application. After completing the tutorial and testing on my development environment I notice that my smtp settings are interferring with my contact us form. Basically I just want send a message to an email address so I dont need the sender mail address for this. I tried removing the SMTP settings in my development.rb file but then I get this error when clicking the submit button:
Errno::ECONNREFUSED in MessagesController#create
Connection refused - connect(2) for "localhost" port 1025
I tried solving in different ways but I come back to this same error. Here's my code:
model/message.rb:
class Message
include ActiveModel::Model
attr_accessor :name, :email, :body
validates :name, :email, :body, presence: true
end
Here's my message controller:
class MessagesController < ApplicationController
def new
#message = Message.new
end
def create
#message = Message.new message_params
if #message.valid?
MessageMailer.contact_me(#message).deliver_now
redirect_to new_message_url, notice: "Message received"
else
render :new
end
end
def message_params
params.require(:message).permit(:name, :email, :body)
end
end
My view:new.html.erb:
<%= form_for #message, url: create_message_url do |f| %>
<%= notice %>
<%= #message.errors.full_messages.join(', ') %>
<%= f.text_field :name, placeholder: 'name' %>
<%= f.email_field :email, placeholder: 'email' %>
<%= f.text_area :body, placeholder: 'body' %>
<%= f.submit 'Send' %>
<% end %>
My Mailer:
class MessageMailer < ApplicationMailer
def contact_me(message)
#greeting = 'Hi'
#body = message.body
mail to: "notifications#example.com", from: message.email
end
end
And my Development.rb/SMTP settings code:
config.action_mailer.delivery_method = :smtp
config.action_mailer.default_url_options = { host: 'localhost', port: 3000 }
config.action_mailer.perform_deliveries = true
config.action_mailer.raise_delivery_errors = true
config.action_mailer.default :charset => "utf-8"
config.action_mailer.smtp_settings = {
:address => 'localhost',
:port => 587,
:domain => 'localhost:3000',
:user_name => 'example#gmail.com',
:password => '######',
:authentication => 'plain',
:enable_starttls_auto => true
}
I just want to get rid of the smtp settings but unfortunately I cannot, is there any way to override these settings or an alternate solution or am I missing something,
Any help will be appreciated,
Thanks in advance
Related
I'm trying to build a contact form in Rails without storing the mails in my database. But I'm getting an undefined method 'name' for nil:NilClass error when I send the form.
My MessagesController
def create
#message = Message.new(message_params)
if #message.valid?
# TODO send message here
Messages.new_messages_email(#mailer).deliver
redirect_to root_url, notice: "Message sent! Thank you for contacting us."
else
redirect_to root_url, notice: "Something went wrong, try again!"
end
end
private
def message_params
params.require(:message).permit(
:name,
:message,
:email
)
end
My Messages model
class Message
include ActiveModel::Validations
include ActiveModel::Conversion
extend ActiveModel::Naming
attr_accessor :name, :email, :message
validates_presence_of :name
validates :email, :email_format => {:message => 'is not looking good'}
validates_length_of :message, :maximum => 500
def initialize(attributes = {})
attributes.each do |name, value|
send("#{name}=", value)
end
end
def persisted?
false
end
end
The email body
!!!
%html
%body
%p
= #mailer.name
Schreef het volgende:
%p= #mailer.message
%p= #mailer.email
And in my routes I have
resources :messages
I forgot to post my Messages mailer
class Messages < ActionMailer::Base
default from: "info#domein.nl"
def new_messages_email(mailer)
#mailer = mailer
mail(to: 'peter#no-illusions.nl',
subject: 'Iemand wilt contact met U')
end
end
For completion my form,
= form_for #message do |f|
.field
%br/
= f.text_field :name, :placeholder => "Naam"
.field
%br/
= f.text_field :email, :placeholder => "Emailadres"
.field
%br/
= f.text_area :message, :rows => 5, :placeholder => "Uw bericht"
.actions= f.submit "Verstuur bericht", :id => "submit"
In my MessagesController I define the paramaters for the create function, but there's something I'm doing wrong, forgetting or overlooking which causes the error.
In your controller should be probably:
Messages.new_messages_email(#message).deliver # not #mailer
Besides that, you have to reinitialize #message within your mailer, e.g:
class Messages < ActionMailer::Base
def new_messages_email(msg)
#message = msg
end
end
I am new to Rails and trying to get a example working to register with a confirmation email with Rails 4 and devise. I am using this example:
https://github.com/mwlang/lazy_registration_demos
I created the following files:
initialisers/setup_mail.rb
ActionMailer::Base.delivery_method = :smtp
ActionMailer::Base.smtp_settings = {
:address => "smtp.gmail.com",
:port => 587,
:domain => "gmail.com",
:user_name => "account#gmail.com",
:password => "passwork",
:authentication => "plain",
:enable_starttls_auto => true
}
/app/mailers/welcome_email.rb
class WelcomeMailer < ActionMailer::Base
def registration_confirmation(user)
mail :to => user, :from => "email#domain.com", :subject => "Subject line"
end
end
/devise/mailer/confirmations_instructions.html.erb
<p>
Welcome #{#email}!
</p>
<p>You can confirm your account email through the link below:</p>
<p>
<%= link_to 'Confirm my account', confirmation_url(#resource, :confirmation_token => #resource.confirmation_token) %>
</p>
confirmations_controller.rb
class ConfirmationsController < Devise::ConfirmationsController
# Remove the first skip_before_filter (:require_no_authentication) if you
# don't want to enable logged users to access the confirmation page.
skip_before_filter :require_no_authentication
skip_before_filter :authenticate_user!, except: [:confirm_user]
def update
with_unconfirmed_confirmable do
if confirmable_user.blank_password?
confirmable_user.update_password(params[:user])
if confirmable_user.valid?
do_confirm
else
do_show
confirmable_user.errors.clear # prevent rendering :new
end
else
self.class.add_error_on(self, :email, :password_allready_set)
end
end
render 'devise/confirmations/new' unless confirmable_user.errors.empty?
end
def confirm_user
if confirmation_token && (#confirmable_user = User.find_by(:confirmation_token => confirmation_token))
do_show
else
flash[:error] = "Invalid confirmation token"
redirect_to :unconfirmed
end
end
def show
with_unconfirmed_confirmable do
confirmable_user.blank_password? ? do_show : do_confirm
end
unless confirmable_user.errors.empty?
self.resource = confirmable_user
render 'devise/confirmations/new'
end
end
protected
def confirmation_token
#confirmation_token ||= params["user"] && params["user"]["confirmation_token"] || params["confirmation_token"]
end
def confirmable_user
#confirmable_user ||= User.find_or_initialize_with_error_by(:confirmation_token, confirmation_token)
end
def with_unconfirmed_confirmable
unless confirmable_user.new_record?
confirmable_user.only_if_unconfirmed {yield}
end
end
def do_show
self.resource = confirmable_user
render 'devise/confirmations/show'
end
def do_confirm
confirmable_user.confirm!
set_flash_message :notice, :confirmed
sign_in_and_redirect(resource_name, confirmable_user)
end
end
/devise/registrations/new.html.haml
%h2 Sign up
= form_for(resource, :as => resource_name, :url => registration_path(resource_name)) do |f|
= devise_error_messages!
%div
= f.label :email
= f.email_field :email, :autofocus => true
%div{style: "margin-top: 25px"}= f.submit "Sign up", class: "btn btn-primary btn-large"
%hr
= render "devise/shared/links"
To trigger the email to be send I need to add
WelcomeMailer.registration_confirmation(#user).deliver
But I have no clue where I need to add this trigger. Do I need to do this in the controller? Or in the view?
Thanks a lot
Managed to fix this issue myself using mailcatcher
Steps to fix:
clone github project lazy_registrations
gem install mailcatcher
add lines to /environments/development.rb
config.action_mailer.delivery_method = :smtp
config.action_mailer.smtp_settings = { :address => "localhost", :port => 1025 }
run mailcatcher
check email using 127.0.0.1:1080
ignore all other code above, just needed a night of sleep :)
hello I' am new at ruby on rails and I am trying to implement an email sender. I would like the email sender to send an email every time somebody types their email. But is not working for some reason, please help me.
class ZipMailer < ActionMailer::Base
default from: "Example#gmail.com"
def zip_email_confirmation(zip_mailer)
recipents zip_mailer
from "Example#gmail.com"
subject "Thanks from Example"
body :zip_mailer => zip_mailer
end
end
ActionMailer::Base.smtp_settings = {
:address =>"smtp.gmail.com",
:port =>587,
:domain =>"gmail.com",
:user_name =>"gmail",
:password =>"12345",
:authentication =>"plain",
:enable_starttls_auto => true
}
def create
#box = Box.new(box_params)
#TO DO: validations. return errors or save
if #box.save
ZipMailer.zip_email_confirmation(#zip_mailer).deliver
ConfirmMailer.box_alert(#box).deliver
session[:box_id] = #box.id
render 'charges/new'
else
render action: 'new'
end
<%= form_tag do %>
<%= email_field(:zip_mailer, :address) %>
<%= submit_tag("sub") %>
<% end %>
First off, i know attr_accessible is deprecated in Rails 4, but what about attr_accessor?
When you hit submit it's returning a "Template is Missing" error, but that's because its hitting an error somewhere in the send proccess then just trying to return "connect#create" which doesn't exist as a physical page.
When i check the log files, I am getting a 500 internal server error when trying to send a contact form, and I'm not sure if using attr_accessor in Rails 4 is the culprit. Is there a newer way to write this?
class Message
include ActiveModel::Validations
include ActiveModel::Conversion
extend ActiveModel::Naming
attr_accessor :name, :email, :phone, :subject, :company, :title, :market, :body
validates :name, :email, :subject, :company, :body, :presence => true
validates :email, :format => { :with => %r{.+#.+\..+} }, :allow_blank => true
def initialize(attributes = {})
attributes.each do |name, value|
send("#{name}=", value)
end
end
def persisted?
false
end
end
The above is the message model for the contact form:
Is it something within the process of sending the data?
The rest of the code for the contact mail functionality is:
Contact Mailer
class ContactMailer< ActionMailer::Base
default :from => "noreply#test.com"
default :to => "{{MY EMAIL}}"
def new_message(message)
#message = message
mail(:subject => "Test Message")
end
end
In /views/contact_mailer/ there is a new_message.text.erb file:
Name: <%= #message.name %>
Email: <%= #message.email %>
Phone: <%= #message.phone %>
Subject: <%= #message.subject %>
Company: <%= #message.company %>
Title: <%= #message.title %>
Market: <%= #message.market %>
Body: <%= #message.body %>
My Routes are:
match 'connect' => 'connect#index', :as => 'connect', :via => :get
match 'connect' => 'connect#create', :as => 'connectpost', :via => :post
The connect page controller:
class ConnectController < ApplicationController
def index
#message = Message.new
end
def create
#message = Message.new(params[:message])
if #message.valid?
NotificationsMailer.new_message(#message).deliver
redirect_to(connect_path, :notice => "Message was successfully sent.")
else
flash.now.alert = "Please fill all fields."
render :new
end
end
end
And finally....the SMTP settings in /config/initializers/smtp_settings.rb
ActionMailer::Base.smtp_settings = {
:address => "smtp.gmail.com",
:port => 587,
:domain => "{{SITE DOMAIN}}",
:user_name => "{{GMAIL EMAIL}}",
:password => "{{GMAIL EMAIL PASSWORD}}",
:authentication => "plain",
:enable_starttls_auto => true
}
My ConnectController#Create was trying to initialize
NotificationMailers.new_message()
But it needed to be:
ContactMailer.new_message()
I have no idea why the tutorial I followed would have the wrong class name there...but that was the issue.
Thanks all.
attr_accessor, attr_writer and attr_reader are all part of vanilla core Ruby and are helper methods for Modules and Classes.
They work fine in Ruby 2.0, so you'll have to mark them off your suspect list.
I am trying to create a contact the form gets submitted. But I don't receive any email.
In my config/application.rb I have addded.
config.action_mailer.raise_delivery_errors = true
config.action_mailer.delivery_method = :smtp
ActionMailer::Base.smtp_settings = {
:address => "mail.vinderhimlen.dk",
:port => 587,
:user_name => "asd#vinderhimlen.dk",
:password => "x",
:authentication => :login
}
My form:
<%= simple_form_for [#support], :url => { :action => "create" }, :html => { :method => :post } do |f| %>
<%= f.input :sender_name, :label => 'Navn' %>
<%= f.input :email, :label => 'E-mail' %>
<%= f.input :support_type, :collection => ['Feedback', 'Idé', "Rapporter fejl", 'Business', 'Andet'], :prompt => "Valg type", :label => 'Erinde' %>
<%= f.label :Besked %>
<%= f.text_area :content, :label => 'Besked', :style => 'width:500px;', %>
<%= f.submit "submit", :value => 'Send besked' %>
<% end %>
My Supportscontroller:
class SupportsController < ApplicationController
def new
# id is required to deal with form
#support = Support.new(:id => 1)
end
def create
#support = Support.new(params[:support])
if #support.save
redirect_to('/', :notice => "Support was successfully sent.")
else
flash[:alert] = "You must fill all fields."
render 'new'
end
end
end
My Support model:
class Support
include ActiveModel::Validations
validates_presence_of :email, :sender_name, :support_type, :content
# to deal with form, you must have an id attribute
attr_accessor :id, :email, :sender_name, :support_type, :content
def initialize(attributes = {})
attributes.each do |key, value|
self.send("#{key}=", value)
end
#attributes = attributes
end
def read_attribute_for_validation(key)
#attributes[key]
end
def to_key
end
def save
if self.valid?
Notifier.support_notification(self).deliver
return true
end
return false
end
end
My config/enviroments/devolpment:
Konkurranceportalen::Application.configure do
# Settings specified here will take precedence over those in config/application.rb
# In the development environment your application's code is reloaded on
# every request. This slows down response time but is perfect for development
# since you don't have to restart the webserver when you make code changes.
config.cache_classes = false
# Log error messages when you accidentally call methods on nil.
config.whiny_nils = true
config.perform_delivery = true
# Show full error reports and disable caching
config.consider_all_requests_local = true
config.action_view.debug_rjs = true
config.action_controller.perform_caching = false
# Don't care if the mailer can't send
config.action_mailer.raise_delivery_errors = true
# Print deprecation notices to the Rails logger
config.active_support.deprecation = :log
# Only use best-standards-support built into browsers
config.action_dispatch.best_standards_support = :builtin
end
My rails log on when submitting the form:
Started POST "/supports" for 127.0.0.1 at 2011-05-31 11:15:35 +0200
Processing by SupportsController#create as HTML
Parameters: {"utf8"=>"Ô£ô", "authenticity_token"=>"bn05TaU4o6TwLVwYH0PgnDyYouo
P1HptzW3HHY2QV/s=", "support"=>{"sender_name"=>"asdasd", "email"=>"ssad#sazdasd.
dk", "support_type"=>"Id├®", "content"=>"asdasd"}, "commit"=>"Send besked"}
←[1m←[36mSQL (0.0ms)←[0m ←[1mSELECT SUM(`tags`.`konkurrancers_count`) AS sum_
id FROM `tags`←[0m
←[1m←[35mSQL (8.0ms)←[0m describe `kategoris_konkurrancers`
←[1m←[36mKonkurrancer Load (1.0ms)←[0m ←[1mSELECT `konkurrancers`.* FROM `kon
kurrancers`←[0m
←[1m←[35mCACHE (0.0ms)←[0m SELECT `konkurrancers`.* FROM `konkurrancers`
←[1m←[36mTag Load (1.0ms)←[0m ←[1mSELECT `tags`.* FROM `tags`←[0m
Rendered notifier/support_notification.html.erb (1.0ms)
Sent mail to asd#vinderhimlen.dk (1752ms)
Date: Tue, 31 May 2011 11:15:39 +0200
From: ssad#sazdasd.dk
To: asd#vinderhimlen.dk
Message-ID: <4asdqweb124ce_16cc85248bc677b3#Home-Pc.mail>
Subject: =?UTF-8?Q?New_Id=C3=A9?=
Mime-Version: 1.0
Content-Type: text/html;
charset=UTF-8
Content-Transfer-Encoding: quoted-printable
=EF=BB=BFhello world!
asdasd=
Redirected to http://localhost:3000/
Completed 302 Found in 4503ms
To trigger mails in dev mode, add this to your development.yml file:
config.action_mailer.perform_deliveries = true