Barna Kovacs
Barna Kovacs

Reputation: 1276

How to trigger email? rails

I would like to trigger a mailer 'action' in a @post view.

class UserMailer < ActionMailer::Base
  default from: "[email protected]"

  def newsletter(post)
    @greeting = ""
    @users = User.all
    @users.each do |user|
      mail to: user.email, subject: post.title
    end
  end
end

  = button_to 'Deliver' do
    UserMailer.newsletter(@post).deliver
  end

If I press this button it pops up the error "No route matches posts/6" when it's clearly exist.

Upvotes: 1

Views: 1000

Answers (1)

user946611
user946611

Reputation:

You have to write an action, which will call UserMailer.newsletter(@post).deliver

def send_newsletter
  @post = Post.find params[:id]
  UserMailer.newsletter(@post).deliver
  render :nothing => true 
end

Add the necessary route, and link the button to that action

In routes.rb

resources :posts do
  member do
    get :send_newsletter
  end
end

In view

link_to 'Deliver', send_newsletter_post_path(@post)

Further, you can change get method to post and submit a form for sending the newsletter

Upvotes: 2

Related Questions