Tuesday, December 1, 2009

Ruby on Rails : Send Email

1. Configuration

add few lines in config/environment.rb
ActionMailer::Base.delivery_method = :smtp
ActionMailer::Base.raise_delivery_errors = true
ActionMailer::Base.smtp_settings = {
:address => "smtp.myserver.com",
:port => 25,
:user_name => "myusername",
:password => "mypassword",
:authentication => :login
}


2. Generating a Mailer

To use Action Mailer, you need to create a mailer model.
$ script/generate mailer UserMailer
exists app/models/
create app/views/user_mailer
exists test/unit/
create test/fixtures/user_mailer
create app/models/user_mailer.rb
create test/unit/user_mailer_test.rb


3. Edit the Model

app/models/user_mailer.rb contains an empty mailer:
class UserMailer < ActionMailer::Base
end

Let’s add a method called welcome_email, that will send an email to the user’s registered email address:
class UserMailer < ActionMailer::Base
def welcome_email(recipient, sender, subject, sent_at = Time.now)
@subject = subject
@recipients = 'no-reply@yourdomain.com'
@from = 'no-reply@yourdomain.com'
@sent_on = sent_at
@body = { :name => recipient, :sender => sender }
end
end


4. Create a Mailer View

Create a file called welcome_email.html.erb in app/views/user_mailer/. This will be the template used for the email, formatted in HTML:
<h1>Welcome to example.com, <%= @name %></h1>
<p>You have successfully signed up to example.com</p>

<p>Thanks for joining and have a great day!</p>

Regards,
<%= @sender %>


5. Invoke the deliver_* method

The arguments passed here will be routed to the mailer model object as well. So to send our email from whatever part of the code we want all we have to do is this:
def welcome
recipient = 'John'
sender = 'Mary'
subject = 'Welcome to Example.com'
UserEmailer.deliver_welcome_email(recipient, sender, subject)

flash[:notice] = 'Email Sent Successfully.'
redirect_to('/people')
end


ActionMailer Class Library : http://api.rubyonrails.org/classes/ActionMailer/Base.html

No comments:

Post a Comment