1. Computing

Discuss in my forum

How to Send Email with Ruby on Rails

By

Email messages are a perfect match for Ruby's strict object orientation — each email an instance of a general Email class —, and the message contents fit Rail's template approach perfectly — many of the emails you send from your web-based app will be very similar. A match made in programmer heaven, sending mail from Ruby on Rails can still be a bit more tricky than anticipated. But by no means is it hard, and the flexibility is awesome.

Send Email with Ruby on Rails

To send an email message from a Ruby on Rails app:

First, create a mailer for use in your application.

  • Open a terminal or command prompt window.
  • From your Rail application's home directory, run ./script/generate mailer MyMailer.

Configuration

Configure the mailer for your system.

  • Open config/environment.rb in a text editor.
  • Add the following to the bottom of the file:
    config.action_mailer.delivery_method = :smtp ActionMailer::Base.server_settings = {   :address => "smtp.example.com",   :port => 25,   :user_name => "username",   :password => "password",   :authentication => :plain }

Adjust the settings for your needs. If your SMTP server does not require authentication, remove the :user_name, :password and :authentication lines altogether. For more options, see the ActionMailer::Base class documentation.

A Method for a Message

It's high time to create the method in the MyMailer class that sets the stage for messages being sent.

  • Open app/models/my_mailer.rb in an editor.
  • Add the following method:
      def mail(recipient)     @from "sender.address@example.com"     @recipients recipient     @subject "Hi #{recipient}"     @body(:recipient => recipient)   end

The Message Template

The message body will be taken from an ActionView template, in which the body parameters from above are available.

  • Create app/views/my_mailer/mail.rhtml and open it in a text editor.
  • Type something like:
    Hi <%= @recipient %>, your inspirational thought for the day...

Creating and Sending a Message

Finally, call the (automatically generated) deliver_mail() class method from the desired controller:

  • Open the desired controller .rb file in an editor.
  • Add the following code to the desired method:
      def email_sent     MyMailer::deliver_mail("recipient.address@example.com")   end

To send an email from vanilla Ruby, you can use the Net::SMTP class.

Related Video
Create Email Aliases and Forwarding Addresses in Gmail

©2014 About.com. All rights reserved.