将数据传递给Rails中的邮件程序守护程序?

时间:2009-08-26 23:31:05

标签: ruby-on-rails daemon actionmailer

根据Rails API(下面的代码段),接收邮件的最佳方式是在守护程序中创建一个Rails实例,每当新邮件到达时,该守护程序都会被MTA调用。

我的问题是:当新邮件到达时,如何将数据传递给该守护进程?

========================

Rails API代码段

To receive emails, you need to implement a public instance method called receive that takes a tmail object as its single parameter. The Action Mailer framework has a corresponding class method, which is also called receive, that accepts a raw, unprocessed email as a string, which it then turns into the tmail object and calls the receive instance method.

Example:

  class Mailman < ActionMailer::Base
    def receive(email)
      page = Page.find_by_address(email.to.first)
      page.emails.create(
        :subject => email.subject, :body => email.body
      )

      if email.has_attachments?
        for attachment in email.attachments
          page.attachments.create({
            :file => attachment, :description => email.subject
          })
        end
      end
    end
  end

This Mailman can be the target for Postfix or other MTAs. In Rails, you would use the runner in the trivial case like this:

  ./script/runner 'Mailman.receive(STDIN.read)'

However, invoking Rails in the runner for each mail to be received is very resource intensive. A single instance of Rails should be run within a daemon if it is going to be utilized to process more than just a limited number of email. 

1 个答案:

答案 0 :(得分:0)

在您提供的示例中,没有运行守护程序来处理电子邮件。文档说您可以设置邮件程序守护程序,在这种情况下为Postfix,以便在收到邮件时调用命令。当您从邮件程序中调用命令时:

RAILS_ROOT / script / runner'Mailman.receive(STDIN.read)'

电子邮件的内容将传递到receive方法中。处理传入电子邮件的更好方法是创建一个接收电子邮件的实际邮箱。然后,您可以编写一个批处理检查邮箱以处理电子邮件的Ruby脚本。您可以通过cron调用该脚本并锁定它,以确保只有一个进程执行此任务。