如何在没有模板的情况下使用rails发送邮件?

Joh*_*hir 42 ruby email ruby-on-rails actionmailer

在我的Rails 3项目中,我想发送一些简单的通知电子邮件.我不需要为它们制作模板或做任何逻辑.我只是想从系统的各个地方解雇他们.

如果我在任意ruby脚本中这样做,我会使用小马.但是,我仍然希望使用rails邮件工具和配置,这样我就能获得与系统中其余邮件相同的可靠性和设置.

最简单的方法是什么?理想情况下会有一些方法

ActionMailer.send(:to => 'foo@example.com', :subject =>"the subject", :body =>"this is the body")
Run Code Online (Sandbox Code Playgroud)

小智 103

在没有模板的情况下在rails 3中发送邮件的最简单方法是调用mail方法ActionMailer::Base直接跟随deliver方法,

例如,以下内容将发送纯文本电子邮件:

ActionMailer::Base.mail(from: "me@example.com", to: "you@example.com", subject: "test", body: "test").deliver
Run Code Online (Sandbox Code Playgroud)

http://api.rubyonrails.org/classes/ActionMailer/Base.html#method-i-mail为您提供所有标题选项以及有关如何使用text/plain和text/html发送多部分/备用电子邮件的想法零件直接.


kle*_*lew 9

以下是Rails Guides使用render方法的一些例子.我没有尝试过,但如果它render在cotrollers中工作,那么你可以使用:

render :text => "Your message"
Run Code Online (Sandbox Code Playgroud)

要么

render :text => my_message
Run Code Online (Sandbox Code Playgroud)

my_message参数在哪里?

您可以将其包装在一个方法中,您可以从所需的每个地方调用它.

更新了Rails 3.2.8

在这个版本的Rails中我必须这样做:

def raw_email( email, subject, body )
  mail(
    :to => email,
    :subject => subject
  ) do |format|
    format.text { render :text => body }
  end
end
Run Code Online (Sandbox Code Playgroud)


Joh*_*hat 7

你可以尝试这样的事情:

class Notifier < ActionMailer::Base
  def send_simple_message(options)
    mail(options.except(:body)) do |format|
      format.text { render :text => options[:body] }
    end.deliver
  end
end
Run Code Online (Sandbox Code Playgroud)

  • 我认为“deliver”不应该出现在邮件程序的方法中。相反,应该在使用邮件程序期间调用它,就像默认邮件程序使用一样 (2认同)

aro*_*roo 5

Rails 5用户可能会发现接受的答案(使用format.text {...})无效。至少我遇到了一个例外,因为Rails在寻找视图。

事实证明,Rails指南中有一个部分称为“不发送模板渲染就发送电子邮件”,而所有需要做的就是为提供:content_type和:body选项mail()。例如:

class UserMailer < ApplicationMailer
  def welcome_email
    mail(to: params[:user].email,
         body: params[:email_body],
         content_type: "text/html",
         subject: "Already rendered!")
  end
end
Run Code Online (Sandbox Code Playgroud)