简体   繁体   中英

How do I use JavaScript to send an email with the Rails 3 Action Mailer?

I'm using the Facebook Comments social plugin and I want to be able to send an email every time someone adds a new comment. In the past, I've used Rails' Action Mailer to send emails, but I can't figure out how to get it to work.

I'm listening for the JavaScript event FB.Event.subscribe('comment.create) then I want the callback function to send an AJAX request to the ActionMailer to send out an email. How do I do this?

JavaScript code:

FB.Event.subscribe('comment.create', commentMailer(response))

function commentMailer(response) {
    //code to call function to send mail
}

Rails code:

class UserMailer < ActionMailer::Base
 default :from => "<email address>"


  def new_comment_email(user, ride)
    @user = user
    @ride = ride
    emails = ride.users.collect {|user| user.email}
    mail(:to => emails, :subject => "etc")
  end
end

I would probably just have a hidden form that I would submit in the commentMailer callback. It would hit an action in a mailer_controller controller that would deliver the mail to the desired recipients.

The advantage of having a hidden form is that you won't have to create the url you want to POST to in the javascript.

Create a controller with only a create action. POST your event to that controller's create action whose only purpose is to invoke ActionMailer and sends the e-mail. You'll get the ability to double-check the data you're posting on the server as a bonus.

Remember, controllers don't need to map 1:1 to models.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM