Rails, Contact_us: Net::SMTPFatalError (550-Your FROM address - ruby-on-rails

I'm using contact_us gem and it was working well until I added another mailer. The second mailer is working well but the contact_us form works just when the email field is my default from email in another mailer! Here are the files and settings:
contact_us.rb
# Use this hook to configure contact mailer.
ContactUs.setup do |config|
# ==> Mailer Configuration
# Configure the e-mail address which email notifications should be sent from. If emails must be sent from a verified email address you may set it here.
# Example:
# config.mailer_from = "contact#please-change-me.com"
config.mailer_from = nil
# Configure the e-mail address which should receive the contact form email notifications.
config.mailer_to = "hi#mysite.com"
# ==> Form Configuration
# Configure the form to ask for the users name.
config.require_name = false
# Configure the form to ask for a subject.
config.require_subject = false
# Configure the form gem to use.
# Example:
# config.form_gem = 'formtastic'
config.form_gem = nil
# Configure the redirect URL after a successful submission
config.success_redirect = '/'
end
application_mailer.rb
class ApplicationMailer < ActionMailer::Base
end
my_mailer.rb
class MyMailer < ApplicationMailer
default from: "\"mysite\" <hi#mysite.com>"
layout 'mailer'
#The email that should be sent to the Passenger after his successful payment
def payment_confirmation(user, trip, seats, code)
...
mail(to: #user.email, subject: "...")
end
end
and my contact_us form is like this:
<% #contact = ContactUs::Contact.new %>
<%= form_for #contact, :url => contacts_path, :id => "contact-form", :html => {:class => 'formtastic'} do |f| %>
<div class="input-group name-email">
<div class="input-field">
<%= f.text_field :name, :id => "name", :placeholder => "نام", :class => "form-control" %>
</div>
<div class="input-field">
<%= f.text_field :email, :id => "email", :placeholder => "ایمیل*", :class => "form-control" %>
<% if f.object.errors[:email].present? %>
<p class='inline-error'><%= f.object.errors[:email].join(' and ') %></p>
<% end %>
</div>
</div>
<div class="input-group">
<%= f.text_area :message, :id => "message", :placeholder => "پیغام*", :class => "form-control" %>
</div>
<div class="input-group">
<%= f.submit "ارسال پیغام", :id => "form-submit", :class => "pull-left" %>
</div>
<% end %>
So, the problem is that it works only when the user submits hi#mysite.com as his mail address in the contact_us form!!
Any idea and help would be appreciated ...

Related

No route matches {:action=>"partner_update", :controller=>"users"}

i'm new in rails so i tried to do this to add a role, making a form to update and if the user update succsessfully add the role.
note: i'm using devise and rolify with cancancan
routes
get 'users/becomepartner' => 'users#becomepartner' do
collection do
patch 'update_partner'
end
end
and this is my users controller
def becomepartner
#user = current_user
end
def update_partner
#user = User.find(current_user.id)
if #user.update_with_password(partner_params)
self.add_role(:partner)
# Sign in the user by passing validation in case their password changed
bypass_sign_in(#user)
redirect_to root_path, notice: 'now you can create'
else
render :becomepartner
end
end
private
def partner_params
# NOTE: Using `strong_parameters` gem
params.require(:user).permit(:name, :style, :current_password, :email)
end
and this is my view becomepartner.html
<div>
<%= form_for(#user, :url => { :action => "update_partner" } ) do |f| %>
<div class="field">
<%= f.label :style %>
<%= f.text_field :style %>
</div>
<div class="field">
<%= f.label :name %>
<%= f.text_field :name %>
</div>
<div class="field">
<%= f.label :email %>
<%= f.email_field :email %>
</div>
<div class="field">
<%= f.label :current_password %> <i>(we need your current password to confirm your changes)</i>
<%= f.password_field :current_password, autocomplete: "off" %>
</div>
<% end %>
</div>
In form action you have mentioned action as partner_update but you don't have that action. Change it to update_partner.
You are using the collection route for another individual route, that is get 'users/becomepartner'. So this will generate the collection route with url like:
users/becomepartner/update_partner
You can confirm this by running rake routes.
But your forms action url will be different.
What you can do is create this collection route inside users resource route like:
resources :users do
collection do
patch 'update_partner'
end
end
Then in form_for url option, use update_partner_users_path
If you don't want the users resources routes, then just define a single route like:
get 'users/becomepartner' => 'users#becomepartner'
patch 'user/update_partner' => 'users#update_partner'
I have not ran any of this code, so if there is any syntax error then post it in comment.
In routes.rb,change
patch 'update_partner' to update 'update_partner' and remove collection as you are not operating on a collection.you have added it in a do block,instead add a one liner route path.
in the form,url must be update_partner and NOT partner_update .

uninitialized constant on Rails 4

I'm trying to build my first contact form, that would send someone's name, email and message to my email address to me. I've seen quite a lot of tutorials and answered questions on stackoverflow, but it didn't help me to fix the problem I'm having. I know it has something to do with the routing but I can't figure what and why.
I'm getting the following error:
Routing Error
uninitialized constant ContactController
Here are my files :
routes.rb
match '/send_mail', to: 'contact#send_mail', via: 'post'
match '/mail', to: 'contact#contact', via: 'get'
controllers/contacts_controller.rb
def send_mail
name = params[:name]
email = params[:email]
body = params[:comments]
ContactMailer.contact_email(name, email, body).deliver
redirect_to contact_path, notice: 'Message sent'
end
mailers/contact_mailer.rb
class ContactMailer < ActionMailer::Base
default to: 'mymail#gmail.com'
def contact_email(name, email, body)
#name = name
#email = email
#body = body`enter code here`
mail(from: email, subject: 'Contact Request')
end
end
views/contact.html.twig
<div class="container-content">
<div class="container">
<%= form_tag(send_mail_path) do %>
<div class="form-group">
<%= label_tag 'name', 'Name' %>
<%= text_field_tag 'name', nil, class: 'form-control', placeholder: 'John Doe' %>
</div>
<div class="form-group">
<%= label_tag 'email', 'Email' %>
<%= email_field_tag 'email', nil, class: 'form-control', placeholder: 'johndoe#domain.com' %>
</div>
<div class="form-group">
<%= label_tag 'comments', 'Comments' %>
<%= text_area_tag 'comments', nil, class: 'form-control', rows: 4, placeholder: 'How can I help you?' %>
</div>
<%= submit_tag nil, class: 'btn btn-default btn-about' %>
<% end %>
</div>
</div>
views/contact_email.html.erb
<!DOCTYPE html>
<html>
<head>
<%= stylesheet_link_tag "application", media: "all", "data-turbolinks-track" => true %>
<%= javascript_include_tag "application", "data-turbolinks-track" => true %>
<meta name="viewport" content="width=device-width, initial-scale=1.0">
</head>
<body>
<p>Mail received from <%= "#{ #name } (#{ #email }):" %></p>
<p><%= #body %></p>
</body>
</html>
config/initializers.rb
module Contact
class Application < Rails::Application
config.action_mailer.delivery_method = :sendmail
config.action_mailer.perform_deliveries = true
config.action_mailer.raise_delivery_errors = true
config.active_record.raise_in_transactional_callbacks = true
end
end
initializers/stmp_config.rb
config.action_mailer.smtp_settings = {
:address => "smtp.gmail.com",
:port => 587,
:domain => "gmail.com",
:user_name => "mymail#gmail.com",
:password => "password",
:authentication => :login,
:enable_starttls_auto => true
}
As I'm newbie in the rails world, I'm not sure at all of what I'm doing, but I've seen a lot of tutorials where people had a code similar to mine, but no one seems to have this problem
Where did i go wrong ?
Thank you in advance
You may want to change your routes.rb as follows (contacts instead of contact):
match '/send_mail', to: 'contacts#send_mail', via: 'post'
match '/mail', to: 'contacts#contact', via: 'get'
Thats one way to create a contact form - however its not really a Rails app. Its just an app that happens to be using Rails.
This is how you can use the Rails conventions to make this more robust and less messy.
Model
Lets generate a model and migration:
$ rails g model enquiry name:string email:string body:text
Then we run the migration:
$ rake db:migrate
So why create a model if we are just sending an email? Because email fails. And you don't want to lose important enquiries from potential customers.
We also want our model to validate that the user provides the required fields:
# app/models/enquiry.rb
model Enquiry < ActiveRecord::Base
validates_presence_of :name, :email, :body
validates_format_of :email, with: /\A([^#\s]+)#((?:[-a-z0-9]+\.)+[a-z]{2,})\Z/i
end
Controller
Lets create a RESTful route:
# config/routes.rb
# ...
resources :enquiries, only: [:new, :create]
Note that we are calling it enquiries. Instead of using an procedure oriented send_contact route we have the resource enquiries which gives us conventions for how to show, create and update it.
You can see what routes are generated with $ rake routes.
See Resource Routing: the Rails Default.
Lets create a controller for our new route:
# app/controllers/enquiries_controller.rb
# note controllers use the plural form
class EnquiriesController < ApplicationController
# GET '/enquiries/new'
def new
#enquiry = Enquiry.new
end
# POST '/enquiries'
def create
#enquiry = Enquiry.new(enquiry_params)
if #enquiry.save
ContactMailer.contact_email(name, email, body).deliver
redirect_to root_path, success: 'Thanks for getting in touch, we will look into it ASAP.'
else
render :new
end
end
private
def enquiry_params
params.require(:enquiry).permit(:name, :email, :body)
end
end
View
We also need a form:
# app/views/enquiries/new.html.erb
<%= form_for(#enquiry) do |f| %>
<div class="form-group">
<%= f.label :name %>
<%= f.text_field :name %>
</div>
<div class="form-group">
<%= f.label :email %>
<%= f.email_field :name %>
</div>
<div class="form-group">
<%= f.label :body %>
<%= f.text_area :body %>
</div>
<%= f.submit %>
<% end %>
By using a form builder and a model our form will automatically "play back" the values if the user submits an invalid form.
Your problem in 'ContactController' - it's must be in plural: 'ContactsController'!

Multiple require & permit strong parameters rails 4

In the below case, i am trying to use strong parameters. I want to require email_address, password and permit remember_me fields.
But using like below it only allows the LAST line in the method Ex:- In below case it only take params.permit(:remember_me)
private
def registration_params
params.require(:email_address)
params.require(:password)
params.permit(:remember_me)
end
Another Ex:- In this below case, if i rearrange it like below it will take only params.require(:email_address) where am i going wrong ?
def registration_params
params.require(:password)
params.permit(:remember_me)
params.require(:email_address)
end
UPDATE
Params hash be like
{
"utf8" => "✓",
"email_address" => "test1#gmail.com",
"password" => "password123",
"remember_me" => "true",
"commit" => "Log in",
"controller" => "registration",
"action" => "sign_in"
}
Ok found the answer through a friend ...one way to do this is
params.require(:email_address)
params.require(:password)
params.permit(
:email_address,
:password,
:remember_me
)
Works good.
Stong parameters are to prevent mass-assignment to Active Record models. Your parameters should be set up in a model backed form. Example from the Michael Hartl Tutorial:
REGISTRATION FORM
<%= form_for(#user) do |f| %>
<%= f.label :name %>
<%= f.text_field :name %>
<%= f.label :email %>
<%= f.email_field :email %>
<%= f.label :password %>
<%= f.password_field :password %>
<%= f.label :password_confirmation, "Confirmation" %>
<%= f.password_field :password_confirmation %>
<%= f.submit "Create my account", class: "btn btn-primary" %>
<% end %>
This will create a parameter that looks like:
PARAMS
{
"utf8" => "✓",
"user" => { email: "test1#gmail.com", name:"Test Name", password: "password", password_confirmation: "password" },
"remember_me" => "true",
"commit" => "Log in",
"controller" => "registration",
"action" => "sign_in"
}
Then in your registration controller you can use strong parameters like:
STRONG PARAMETERS
params.require(:user).permit(:name, :email, :password, :password_confirmation)
It looks like in your case, you are handling a log in, in which case, you only need to use regular parameters to capture the login information.
SESSION CREATION
def sign_in
email = params[:email]
password = params[:password]
if User.authenticate!(email, password)
# do something
else
# do something different
end
end
Edit:
Here is the Rails way for you to handle logins and, I believe, cases where you need to 'require' multiple parameters and provide errors back to the user.
Unlike using strong params, this approach provides feedback to the user (using validation errors) when parameters are missing or blank. This is more user-friendly than throwing an exception.
Create an ActiveModel (not ActiveRecord) form backing object. This form backing object is where you specify which fields are required and when a call to valid? is performed, these fields will be validated.
With this, you will get nice user-friendly errors if:
email is missing
password is missing
email and password do not match
models/session.rb
class Session
include ActiveModel::Model
attr_accessor :password, :email, :remember_me
validates_presence_of :password, :email # these fields are required!
def authenticate
return false unless valid? # this checks that required params
# are present and adds errors to the
# errors object if not
if User.authenticate(:password, :email) # validate credentials
true
else
errors.add(:email, "and password didn't match") # wrong credentials. add error!
false
end
end
end
Create the controller. Here is what your controller would look like for logging in a user:
app/controllers/sessions_controller.rb
class SessionsController < ApplicationController
# GET /login
def new
#session = Session.new
end
# POST /login
def create
#session = Session.new(login_params)
if #session.authenticate
# do whatever you need to do to log the user in
# set remember_me cookie, etc.
redirect_to '/success', notice: 'You are logged in'
else
render :new # shows the form again, filled-in and with errors
end
end
private
def login_params
params.require(:session).permit(:email, :password, :remember_me)
end
end
Set up the view
app/views/sessions/new.html.erb
<% if #session.errors.any? %>
<ul>
<% #session.errors.full_messages.each do |msg| %>
<li><%= msg %></li>
<% end %>
</ul>
<% end %>
<%= form_for #session, :url => login_path do |f| %>
<div>
<%= f.label :email, 'Email:' %>
</div>
<div>
<%= f.text_field :email %>
</div>
<div>
<%= f.label :password, 'Password:' %>
</div>
<div>
<%= f.password_field :password %>
</div>
<div>
<%= f.label :remember_me, 'Remember Me?' %>
<%= f.check_box :remember_me %>
</div>
<div>
<%= f.submit %>
</div>
<% end %>
Lastly, make sure the routes are configured
config/routes.rb
get 'login' => 'sessions#new'
post 'login' => 'sessions#create'
2020 solution:
def registration_params
params.require([:email_address, :password]) #require all of these
params.permit(:email_address, :password, :remember_me) #return hash
end

Name in Sendgrid Email with Rails

I'm using careerfoundry's tutorial on using Sendgrid to send emails with Heroku. I'm using their exact code for the user mailer and thank_you action in the pages controller. This code is working for the most part. The issue is that the subject line I receive in my inbox is this:
A new contact form message from #{name}
User_Mailer.rb
class UserMailer < ActionMailer::Base
default from: "from#example.com"
def contact_form(email, name, message)
#message = message
mail(:from => email,
:to => 'your-email#example.com',
:subject => "A new contact form message from #{name}")
end
end
Contact Form
<%= form_tag("/thank_you") do %>
<div class="row">
<div class="col-md-4">
<div class="input-group">
<%= text_field_tag :name, nil, class: 'form-control', placeholder: 'Name' %>
</div>
</div>
<div class="col-md-8">
<div class="input-group">
<span class="input-group-addon" id="basic-addon1">#</span>
<%= text_field_tag :email, nil, class: 'form-control', placeholder: 'Email' %>
</div>
</div>
</div>
<br>
<div class="row">
<div class="col-md-12">
<div class="input-group text-area-wide">
<%= text_area_tag :message, nil, class: 'form-control text-area-wide', placeholder: 'Message' %>
</div>
</div>
</div>
<br>
<%= submit_tag 'Send Message', class: 'btn btn-success' %>
<% end %>
Pages Controller
def thank_you
#name = params[:name]
#email = params[:email]
#message = params[:message] || "Hello!"
# Only try to send this email on a POST
# if request.post?
# or make a feedback form controller and send in the create action
# ActionMailer::Base.mail( FOR TEST PURPOSES
# :from => #email,
# :to => 'erikvdw#comcast.net',
# :subject => "A new contact form message from #{#name}",
# :body => #message).deliver
UserMailer.contact_form(#email, #name, #message).deliver
end
A quick fix would be to just split the string into two parts as such
class UserMailer < ActionMailer::Base
default from: "from#example.com"
def contact_form(email, name, message)
#message = message
mail(:from => email,
:to => 'your-email#example.com',
:subject => "A new contact form message from " + name) <----
end
end
This way the notation is clearer and it will avoid the manual concatenation problem.
After looking up a quick thing, it seems like this might also work. The single quotes are needed internally apparently according to a couple sources I found. I don't use that notation so let me know if it helped!
:subject => "A new contact form message from '#{name}'")

Rails Deliver on Certain Date?

I am making a little app based on futureme.org for practice. The user goes to a page, sees a form, fills it out with email, subject, message, and a delivery date. Then the app delivers their message (email) on that date.
The problem I am having, is I am not sure how to set up the delivery date option in the model & in the view (ie. does rails have a date option?). Here is my code;
Letter.rb
class Letter < ActiveRecord::Base
VALID_EMAIL_REGEX = /\A[\w+\-,]+#[a-z\d\-.]+\.[a-z]+\z/i
validates_presence_of :email, presence: true, format: { with: VALID_EMAIL_REGEX },
uniqueness: { case_sensitive: false }
validates_length_of :subject, presence: true, :maximum => 30
validates_presence_of :message
validates_presence_of :deliver_on #not sure if this is right
end
Letters_Controller.rb
class LettersController < ApplicationController
def create
#letter = Letter.new(letter_params)
if #letter.save
LetterMailer.letter_confirm(#letter).deliver
redirect_to letters_path, :notice => "Your letter was sent!"
else
render "welcome/home"
end
end
private
def letter_params
params.require(:letter).permit(:email, :subject, :message)
end
end
lettermailer.rb
class Lettermailer < ActionMailer::Base
default from: "futureself#example.com"
def letter_confirm(letter)
mail(to: #letter.email, subject: "Thanks from Future Self")
end
def letter_email(letter)
#letter = letter
#url = 'http://futureself.herokuapp.com'
mail(to: #letter.email, subject: #letter.subject)
end
end
Home Page Form;
<%= form_for #letter, :html => {:class => 'form-horizontal'} do |f| %>
<% if #letter.errors.any? %>
<div class="error_messages">
<h3><%= pluralize(#letter.errors.count, "error")%> stopped this message from being saved</h3>
<ul>
<% #letter.errors.full_messages.each do |msg| %>
<li><%= msg %></li>
<% end %>
</ul>
<% end %>
<div class="field">
<%= f.label :email %><br />
<%= f.text_field :email %>
</div>
<div class="field">
<%= f.label :subject %><br />
<%= f.text_field :subject %><br />
</div>
<div class="field">
<%= f.label :message, "Message" %><br />
<%= f.text_area :message, size: "100x10" %>
</div>
<!-- Deliver on Option -->
<div class="field"><%= f.submit "Submit", class: "btn btn-small btn-primary" %></div>
<% end %>
</body>
</html>
Any help at all would be great.
You need a job queue, I would suggest using DelayedJob as it's about as simple as it gets (if you are using ActiveRecord) https://github.com/collectiveidea/delayed_job
Then in your LessonsController
LetterMailer.delay(run_at: #letter.deliver_on).letter_confirm(#letter)
This assumes deliver_on is a DateTime object.
Couple things you might want to consider:
Rails Cast on DelayedJob http://railscasts.com/episodes/171-delayed-job-revised
if someone changes the letter model before it's delivered
TimeZones http://railscasts.com/episodes/106-time-zones-revised
Server implementation of DelayedJob (can be tricky)
Other job queues that are good but rely on redis are http://sidekiq.org/ and https://github.com/resque/resque
Validations
I like to use the validates_timeliness gem. So you can do things like
validates_date :deliver_on, :before => lambda { Time.zone.now + 1.year },
:before_message => "must be earlier one year from today",
:on_or_after => lambda { Time.zone.now.end_of_day },
:on_or_after_message => "must be after today"
Form
You can use jquery-ui-rails
f.input :deliver_on, as: :string, label: "Date of delivery (dd/mm/yyyy)", input_html: {class: "jquery-ui-date", value: f.deliver_on ? l(f.deliver_on) : nil }
Don't get me started on RegEx for email. Try googling it ;)
And yeah like #mattsmith said check out delayed job.

Resources