How to resolve ActionMailer ignoring? - ruby-on-rails

Hi I'm making user register application by ruby on rails.
But ActionMailer process ignore my code.
When I try to use
UserMailer::confirmation_email.deliver
on rails s, I could send email.
But when I use bellow process, UserMailer::confirmation_email is ignored.
Do you know how to resolve it?
user_controller.rb
class UsersController < ApplicationController
skip_before_action :verify_authenticity_token
def create
user = User.new(user_params)
result = Users::RegisterService.register_user(user)
render result
end
end
register_service.rb
module Users
module RegisterService
module_function
def register_user(user = {})
if user.save
UserMailer::confirmation_email(user)
result = { json: {status: 'User created successfully'}, status: :created }
else
result = { json: { errors: user.errors.full_messages }, status: :bad_request }
end
return result
end
end
end
user_mailer.rb
class UserMailer < ApplicationMailer
default from: 'email#gmail.com'
def confirmation_email(user)
#user = user
#url = 'http://192.16.8.33.10/user/confirm?confirmation_token=' + #user.confirmation_token
mail(
to: #user.email,
subject: 'Welcome to My Awesome Site',
template_name: 'user_confirm'
)
end
end

Call deliver_now to send email right away and deliver_later to send email asynchronously.
UserMailer::confirmation_email(user).deliver_now

Related

How can I set auth header with JWT in Rails?

I'm quite new to RoR programming and stuck while trying to migrate my authentication from Clearance to JWT. I created all of the required methods in ApplicationController and UsersController and even managed to sign up a user, save the user's password_digest to the database and then log in a user (in terms of POST params, I mean that no errors were thrown). However, I fail to keep the user logged in. I understand that there should be an auth_header attached to each request by my user, but how do I create one? I googled it multiple times, but failed to find how to handle it in terms of front-end. Everybody seems to use these fancy apps with buttons to create all the required headers and send raw json data ((
In other words, I have my JWT token encoded in the entrance method (as posted below) but I cannot understand how to pass it as a header in each and every request to the app further on?
users_controller.rb
class UsersController < ApplicationController
def create
#user = User.create(user_params)
if #user.valid?
token = encode_token({ user_id: #user.id })
redirect_to root_path
else
render json: { error: "Invalid email or password"}, status: :unprocessable_entity
end
end
def entrance
#user = User.find_by(email: user_params[:email])
if #user && #user.authenticate(user_params[:password])
token = encode_token({ user_id: #user.id })
redirect_to root_path
else
render json: { error: "Invalid email or password"}, status: :unprocessable_entity
end
end
def login
render 'login'
end
def signup
#user = User.new
render 'signup'
end
application_controller.rb
class ApplicationController < ActionController::Base
helper_method :current_user
def encode_token(payload)
JWT.encode(payload, 'secret')
end
def decode_token
auth_header = request.headers["Authorization"]
if auth_header
token = auth_header.split(' ')[1]
begin
JWT.decode(token, 'secret', true, algorithm: 'HS256')
rescue JWT::DecodeError
nil
end
end
end
def current_user
decoded_token = decode_token()
if decoded_token
user_id = decoded_token[0]['user_id']
#user = User.find(user_id)
end
end
def signed_in?
current_user.present?
end
def authorize
if signed_in?
redirect_to root_path
else
redirect_to "/log_in"
end
end
I truncated the code a bit, but all the relevant methods are included.

Method to send multiple paperclip attachments through actionmailer in rails

So I need my mailer to send attachments that the user uploads in the form upon creation. I used cocoon and paperclip to attach multiple files in the form.
Here is my object_controller:
class RfqsController < ApplicationController
...
def create
#object= Rfq.new(rfq_params)
respond_to do |format|
if #object.save
Object_mailer.object_message(current_user, #object).deliver
format.html { redirect_to #object, notice: 'object was successfully created.' }
format.html { render :new }
end
end
end
...
This will send the email with multiple attachments
class ObjectMailer < ApplicationMailer
default from: "test#test.com"
def placeholder_message(user, rfq)
#user = user
object.object_attachments.each do |attachment|
attachments[attachment.attachment_file_file_name] = File.read(attachment.attachment_file.path)
end
mail to: user.email, subject: "test"
end
end

Using Clearance with API

I am currently using Clearance from Throughbot for my authentication. I am needing to add an API to my product and can't seem to find docs about using Clearance with an API. Is there a certain Header I can set that Clearance will check automatically and if not what can I use? I think I may be able to use this.
To get around this I ended up overriding the authenticate methods on the ApplicationController and the User model. It looks something like this:
class ApplicationController < ActionController::Base
include Clearance::Controller
include Clearance::Authentication
def authenticate(params)
if request.headers['AUTH-TOKEN']
return nil unless user = User.where(remember_token: request.headers['AUTH-TOKEN']).first
sign_in user
else
User.authenticate(params[:session][:email], params[:session][:password])
end
end
#rest of class omitted for bevity
end
Then I subclasses SessionsController to override the create method like so:
class SessionsController < Clearance::SessionsController
def create
#user = authenticate(params)
sign_in(#user) do |status|
respond_to do |format|
if status.success?
format.html { redirect_back_or url_after_create }
format.json { render json: #user, status: :ok }
else
format.html do
flash.now.notice = status.failure_message
render template: 'sessions/new', status: :unauthorized
end
format.json { render json: [errors: status.failure_message], status: :unauthorized }
end
end
end
end
#rest of class omitted for bevity
end
Then all you have to do to test or use is set the requests AUTH-TOKEN header to the users remember token and you're all set. I chose to use the remember token because it is updated whenever the user logs out. You may not want this to happen and could instead generate a auth_token field on your model and change the where to use the new field.

Sending a confirmation email with Rails

I am attempting to send a confirmation email to a newly registered user using Rails 4.0.1 and Ruby 2.0.0.
I am not getting any errors but the mail just is not sending. Here is the relevant code:
config/environments/development.rb
...
config.action_mailer.smtp_settings = {
:authenication=>:plain,
:address=>"smpt.mailgun.org",
:port=>587,
:domain=>"sandboxf4f4c96ebc7b4eb1b6c7475ad4de048c.mailgun.org",
:user_name=>"postmaster#sandboxf4f4c96ebc7b4eb1b6c7475ad4de048c.mailgun.org",
:password=>"6j3c9l35tu33"
}
app/model/user.rb
...
def create
#user=User.new(user_params)
if #user.save
ModelMailer.account_activation(#user).deliver
redirect_to lessons_url
else
render :new
end
end
mailers/model_mailer.rb
class ModelMailer < ActionMailer::Base
default from: "me#sandboxf4f4c96ebc7b4eb1b6c7475ad4de048c.mailgun.org"
def account_activation(user)
#user = user
mail to: "myemail#gmail.com", subject: "Account Activation"
end
end
Any help would be appreciated.

PayPal IPN Send Email

I have a controller that handles PayPal's IPN callback. I want to mark an attendee as 'paid' and send them a confirmation email if they've successfully paid.
The mark paid action is working but the email is not sending.
Here's my controller:
class PaymentNotificationsController < ApplicationController
protect_from_forgery :except => [:create]
def create
PaymentNotification.create!(:params => params, :attendee_id => params[:invoice], :status => params[:payment_status], :transaction_id => params[:txn_id])
if params[:payment_status] == 'Complete'
#attendee = Attendee.find(params[:invoice])
## Working
#attendee.update_attribute(:paid, Time.now)
## Not Working
UserMailer.welcome_email(#attendee).deliver
end
render nothing: true
end
end
Here's my user_mailer file:
class UserMailer < ActionMailer::Base
default from: 'example#email.com'
def welcome_email(user)
#user = user
email_with_name = "#{#user.first_name} #{#user.last_name} <#{#user.email}>"
#url = 'http://example.com'
mail(
to: email_with_name,
subject: 'Welcome to Yadda Yadda'
)
end
end
Here's the weird thing, in another controller that doesn't have PayPal the mailer works:
class VendorsController < ApplicationController
def create
#vendor = Vendor.new(vendor_params)
if #vendor.save
UserMailer.welcome_email(#vendor).deliver
redirect_to vendor_success_path
else
render 'new'
end
end
end
I am pulling your answer out of your question and posting it here for future reference.
This takes two actions (mark paid and send mail). It has been moved to the model as an after_create method.
Here's the model:
class PaymentNotification < ActiveRecord::Base
...
after_create :mark_attendee_paid
private
def mark_attendee_paid
if status == 'Completed'
attendee.update_attribute(:paid, Time.now)
UserMailer.welcome_email(attendee).deliver
end
end
end

Resources