简体   繁体   English

如何使用JavaScript通过Rails 3 Action Mailer发送电子邮件?

[英]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. 我正在使用Facebook Comments社交插件,我希望每次有人添加新评论时都能够发送电子邮件。 In the past, I've used Rails' Action Mailer to send emails, but I can't figure out how to get it to work. 过去,我曾使用Rails的Action Mailer发送电子邮件,但我不知道如何使它正常工作。

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. 我正在监听JavaScript事件FB.Event.subscribe('comment.create)然后希望回调函数向ActionMailer发送AJAX请求以发送电子邮件。 How do I do this? 我该怎么做呢?

JavaScript code: JavaScript代码:

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

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

Rails code: Rails代码:

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. 我可能只有一个隐藏表单,可以在commentMailer回调中提交。 It would hit an action in a mailer_controller controller that would deliver the mail to the desired recipients. 它会在mailer_controller控制器中执行一个动作,该动作会将邮件传递给所需的收件人。

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. 隐藏表单的优点是您不必在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. 将事件发布到该控制器的create动作中,该动作的唯一目的是调用ActionMailer并发送电子邮件。 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. 请记住,控制器不需要将1:1映射到模型。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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