How can I send mail with rails without a template?

John Bachir picture John Bachir · Feb 6, 2011 · Viewed 19.8k times · Source

In my Rails 3 project, I want to send some simple notification emails. I don't need to make a template for them or do any logic. I just want to fire them off from various places in the system.

If I were doing this in an arbitrary ruby script I would use pony. However, I'd like to still use the rails mail facilities and configuration, so that I get the same reliability and setup that I have for the rest of the mail in my system.

What's the most simple way to do this? Ideally there would be some method like

ActionMailer.send(:to => '[email protected]', :subject =>"the subject", :body =>"this is the body")

Answer

KMG picture KMG · Oct 19, 2012

The simplest way to send mail in rails 3 without a template is to call the mail method of ActionMailer::Base directly followed by the deliver method,

For ex, the following would send a plain text e-mail:

ActionMailer::Base.mail(
  from: "[email protected]",
  to: "[email protected]",
  subject: "test",
  body: "test"
).deliver

http://api.rubyonrails.org/classes/ActionMailer/Base.html#method-i-mail gives you all the header options and also ideas about the how to send a multipart/alternative email with text/plain and text/html parts directly.