Rails 2.0 Email (ActionMailer) Example


Does anybody have a simple Rails 2.1 working example of creating an
email from a simple Web form and sending it via ActionMailer? Most of
the examples I've found so far all seem to be Rails 1.x based and
don't work with Rails 2.x.

Best Regards,


ruby script/generate mailer customermailer


class CustomerMailer < ActionMailer::Base

  def welcome_message(sent_at = Time.now)
    @subject = 'CustomerMailer#welcome_message'
    @body = {}
    @recipients = ''
    @from = ''
    @sent_on = sent_at
    @headers = {}
    @body["email"] = ''


This will be your email message

and now send it with this:

customer_mail = CustomerMailer.create_welcome_message

Thanks for the reply, I assume I need to define some configuration
within the environment.rb for this to work?



I find this thread wonderfully useful and interesting...is there a
chance you could show an example of the views/customer_mailer/
welcome_message.html.erb ?
Is customer_mailer a controller also?
I am grateful for a comprehensive example.
Thank you,

Put this in the environment.rb file(I use the google smtp server so I
had to install the action_mailer_tls plugin):

  config.action_mailer.raise_delivery_errors = false
  config.action_mailer.delivery_method = :smtp
  config.action_mailer.default_content_type = "text/html"
  config.action_mailer.default_url_options = { :host =>
"domainname.com" }
  config.action_mailer.smtp_settings = {
    :tls => true,
    :address => "smtp.gmail.com",
    :port => 587,
    :domain => "domainname.com",
    :authentication => :plain,
    :user_name => "username",
    :password => "password"

Here is a snip from new_question_message.html.erb I have:

Question from..: <%= @question.name %><br />
Email..........: <%= @question.email %><br />
<% if @question.phonenumber -%>
Phonenumber....: <%= @question.phonenumber %><br />
<% end -%>
Subject........: <%= @question.subject %><br />
=========================================<br />
<%= @question.description %><br />

Then when I send this I have to pass the object:

mail = CustomerMailer.create_new_question_message(@question)

customer_mailer is not a controller its a actionmailer and it lives in
the /app/models directory

When you use the ruby script/generate mailer customermailer command it
creates that for you.

So the steps would be:

- Create the mailer with generate mailer
- Add a mailer action like welcome_message
- Setup your environment.rb with the correct smtp setup
- add the deliver action to your action in your controller (Imprtant
is to use CustomerMailer.create_ <- )

That should be all you need.

If you don't want to wait for the email to be sent (Sometimes the app
waits a second or 3 to send an email which does not make for a snappy
interface) Watch this http://railscasts.com/episodes/128-starling-and-workling
Starling and Workling works great to offload the email delivery.