2011-02-09 68 views
26

我正在写一个小的Ruby程序,它将从数据库中提取记录并每天发送一封HTML邮件。我正在尝试为此使用ActionMailer 3.0.3,但我遇到了问题。到目前为止,我在Rails之外使用ActionMailer所做的所有搜索都适用于版本3之前的版本。有人可以指出我在哪里找到有关如何执行此操作的资源的正确方向?这里就是我至今对我的邮件文件:ActionMailer 3 without Rails

# lib/bug_mailer.rb 
require 'action_mailer' 

ActionMailer::Base.delivery_method = :file 

class BugMailer < ActionMailer::Base 
    def daily_email 
    mail(
      :to  => "[email protected]", 
      :from => "[email protected]", 
      :subject => "testing mail" 
    ) 
    end 
end 

BugMailer.daily_email.deliver 

我肯定被困在哪里把我的意见。每次尝试将ActionMailer告诉我的模板失败。

我想我也应该问一下,是否有不同的方式去完成这个程序。基本上,我在这一刻从头开始做所有事情。显然是什么让Rails真棒是它的惯例,所以试图单独使用部分Rails来浪费时间?有没有办法让Rails-like的环境没有创建一个完整的Rails应用程序?

回答

44

经过一番认真的调试,我发现如何配置它。

文件mailer.rb

require 'action_mailer' 

ActionMailer::Base.raise_delivery_errors = true 
ActionMailer::Base.delivery_method = :smtp 
ActionMailer::Base.smtp_settings = { 
    :address => "smtp.gmail.com", 
    :port  => 587, 
    :domain => "domain.com.ar", 
    :authentication => :plain, 
    :user_name  => "[email protected]", 
    :password  => "passw0rd", 
    :enable_starttls_auto => true 
    } 
ActionMailer::Base.view_paths= File.dirname(__FILE__) 

class Mailer < ActionMailer::Base 

    def daily_email 
    @var = "var" 

    mail( :to  => "[email protected]", 
      :from => "[email protected]", 
      :subject => "testing mail") do |format| 
       format.text 
       format.html 
    end 
    end 
end 

email = Mailer.daily_email 
puts email 
email.deliver 

文件·邮寄包装/ daily_email.html.erb

<p>this is an html email</p> 
<p> and this is a variable <%= @var %> </p> 

文件·邮寄包装/ daily_email.text.erb

this is a text email 

and this is a variable <%= @var %> 

不错的问题!它帮助我了解更多的是如何Rails 3件的作品:)

+0

谢谢...,帮助。所以,我卡在哪里是我的观点。我知道,如果我正在创建一个Rails应用程序,他们会生活在`app/views`中,但我不知道应该在哪里放置我的视图。现在我的观点如下:`lib/bug_mailer/daily_email.html.erb`。有任何想法吗? – 2011-02-11 21:59:37

2

我花了一段时间来得到这个工作的(非)的Rails 4.我怀疑这只是因为我有“:需要=>假”所有在我的Gemfile,但我需要添加以下,使其工作:

require 'action_view/record_identifier' 
require 'action_view/helpers' 
require 'action_mailer' 

如果没有上面的代码,我一直得到一个NoMethodError与undefined method 'assign_controller'

在那之后,我配置的ActionMailer如下:

ActionMailer::Base.smtp_settings = { 
    address: 'localhost', port: '25', authentication: :plain 
} 
ActionMailer::Base.default from: '[email protected]' 
ActionMailer::Base.raise_delivery_errors = true 
ActionMailer::Base.logger = Logger.new(STDOUT) 
ActionMailer::Base.logger.level = Logger::DEBUG 
ActionMailer::Base.view_paths = [ 
    File.join(File.expand_path("../../", __FILE__), 'views', 'mailers') 
    # Note that this is an Array 
] 

模板去lib/<GEM_NAME>/views/mailers/<MAILER_CLASS_NAME>/<MAILER_ACTION_NAME>.erb(MAILER_ACTION_NAME是你打电话,发送电子邮件的邮件类的公共实例方法)。

最后,不要忘了把这个在您的spec_helper

ActionMailer::Base.delivery_method = :test