Recipe 9.5. Sending Email from a Rails Application


Problem

Contributed by: Dae San Hwang

You want to create and send email from your Rails application.

Let's say a new customer has just filled out a registration form at your web site. You want the complete_registration action in RegistrationController to save the customer's registration information to the database and to send the welcome email.

Solution

This solution uses the CustomerMailer class from Section 9.2."

Sending email using Action Mailer is a two-step process. First, you create a mail object by calling a class method of the mailer class whose name starts with create_. Then you use the class method deliver of the mailer class to actually send the email off to the SMTP server.

app/controllers/registration_controller.rb:

class RegistrationController < ApplicationController   def complete_registration     new_user = User.create(params[:user])     mail = CustomerMailer.create_welcome_message(new_user.name, new_user.email)     CustomerMailer.deliver(mail)   end end

Discussion

Action Mailer internally uses the TMail library, written by Minero Aoki, to create and process emails. For example, the mail variable in the complete_registration action is a TMail::Mail object.

See Also

  • TMail Project home page at http://i.loveruby.net/en/projects/tmail

  • Section 9.2"

  • Section 9.3"




Rails Cookbook
Rails Cookbook (Cookbooks (OReilly))
ISBN: 0596527314
EAN: 2147483647
Year: 2007
Pages: 250
Authors: Rob Orsini

flylib.com © 2008-2017.
If you may any questions please contact us: flylib@qtcs.net