Ruby on rails Rails:如何单独使用ActionMailer?

Ruby on rails Rails:如何单独使用ActionMailer?,ruby-on-rails,ruby,actionmailer,Ruby On Rails,Ruby,Actionmailer,我正在创建一个应用程序,将用于发送电子邮件。我不需要使用常规的邮件发送程序和查看模板,因为我只需要接收用于生成电子邮件的数据。但是,我认为使用ActionMailer而不是直接与SMTP交互有一些好处。我在尝试实例化ActionMailer::Base的新实例时遇到问题。如何在不定义扩展ActionMailer::Base的新类的情况下单独使用ActionMailer?这是一个最基本的解决方案。您必须将smtp设置和硬编码值更改为变量等。这样您就不需要使用视图。如果您仍然想使用ERB,我建议您退

我正在创建一个应用程序,将用于发送电子邮件。我不需要使用常规的邮件发送程序和查看模板,因为我只需要接收用于生成电子邮件的数据。但是,我认为使用
ActionMailer
而不是直接与
SMTP
交互有一些好处。我在尝试实例化
ActionMailer::Base
的新实例时遇到问题。如何在不定义扩展
ActionMailer::Base
的新类的情况下单独使用
ActionMailer

这是一个最基本的解决方案。您必须将smtp设置和硬编码值更改为变量等。这样您就不需要使用视图。如果您仍然想使用ERB,我建议您退房

只需更改此代码,将其放入类似“test_email.rb”的文件中,并使用
ruby test_email.rb

require 'action_mailer'

ActionMailer::Base.smtp_settings = {
  :address              => "smtp.gmail.com",
  :port                 => 587,
  :domain               => "gmail.com",
  :user_name            => "testuser123",
  :password             => "secret",
  :authentication       => "plain",
  :enable_starttls_auto => true
}

class TestMailer < ActionMailer::Base
  default :from => "testuser123@gmail.com"

  # def somemethod()
  #   mail(:to => "John Doe <john@example.com>", :subject => "TEST", :body => "HERE WE GO!!!")
  # end

  def mail(args)
    super
  end
end

# TestMailer.somemethod().deliver
TestMailer.mail(:to => "John Doe <john@example.com>", :subject => "TEST", :body => "HERE WE GO!!!")
要求“操作邮件”
ActionMailer::Base.smtp\u设置={
:address=>“smtp.gmail.com”,
:端口=>587,
:domain=>“gmail.com”,
:user_name=>“testuser123”,
:password=>“secret”,
:身份验证=>“普通”,
:enable_starttls_auto=>true
}
类TestMailer”testuser123@gmail.com"
#def somemethod()
#邮件(:to=>“John Doe”,:subject=>“TEST”,:body=>“开始!!!”)
#结束
def邮件(args)
超级的
结束
结束
#TestMailer.somemethod().deliver
邮件(:to=>“John Doe”,:subject=>“TEST”,:body=>“开始!!!”)

啊,我想我现在更明白了。基本上,您正在寻找一个类似于php的mail()的简单单行程序,对吗

如果是这样的话,ActionMailer对你来说就没有意义了,因为它确实不是这个工作的合适工具

我想你的赢家是一颗叫做小马的红宝石:

例如:

Pony.mail(:to => 'you@example.com', :from => 'me@example.com', :subject => 'hi', :body => 'Hello there.')

ActionMailer的底层功能由提供。这使您可以非常简单地发送邮件,例如:

Mail.deliver do
  from     'me@test.lindsaar.net'
  to       'you@test.lindsaar.net'
  subject  'Here is the image you wanted'
  body     File.read('body.txt')
  add_file :filename => 'somefile.png', :content => File.read('/somefile.png')
end

它支持ActionMailer使用的所有方法进行交付。

这个问题有点让人困惑。您说您正在创建一个RESTful API来发送电子邮件。处理RESTful API的rails应用程序也负责发送电子邮件吗?你说得对,对不起。我更新了问题并删除了关于REST的部分,因为它与我真正的问题无关。为什么不扩展ActionMailer::Base?这就是它的工作原理。@tybro0103因为我不需要视图,也不需要定义为不同方法的不同类型的电子邮件。我所需要的就是
mail()
方法,我可以通过它传递电子邮件中定义的所有值。这就是我正在做的事情。我有一个通用的邮件程序,带有一个通用的“prepare”方法。我想直接调用
mail()
,因为这就是我正在使用的全部。好的,我将代码更改为更通用的代码。这是你想要的,但不是你建议的方式。我知道它有一点开销,但它符合您的规格。您可以覆盖所有内容,没有视图等。默认的from是不相关的,因为您可以在mail()中添加自己的内容。我们可以使用mail gem在邮件正文中使用占位符吗?因此,假设您可以在没有Rails的Ruby脚本中使用它?我发现Rails之外的ActionMailer非常冗长,使用起来有点麻烦。在我的Ruby(但不是Rails)项目中,我也在使用Pony outside。