1. Technology
Send to a Friend via Email
You can opt-out at any time. Please refer to our privacy policy for contact information.

How to Send Email with Ruby


Since the SMTP library is installed when you install Ruby,you don't need to install any gems or libraries. Simply require net/smtp to begin using the SMTP library. Once that's finished, the primary way to use the SMTP library is via the Net::SMTP.start method. This method will perform the connection to the server, do the HELO handshake and get ready to start sending messages. It can also handle PLAIN, LOGIN and CRAM MD5 authentication protocols.

The start method takes at least three arguments. The first is the address of the SMTP relay server. If you're running your own relay server, the address should be localhost. If you're using your ISP's relay server, use their address, which is often mail.isp.com and will be the same SMTP server with which you configure your email clients, such as Outlook or Thunderbird. (If you can't find this address, look in your ISP's knowledge base or help pages.)

The second argument to the start method is the port on which the SMTP server is running--it's almost always port 25. The third argument has to do with the HELO handshake, and will determine if the relay server will relay mail for you. Use the server portion of your email address for this argument. This means, for example, that if your email address is user@isp.com, you'll use isp.com.

The start method returns a Net::SMTP object. Save this object in a variable to use it to send messages. Alternatively, you can pass the start method a block, the argument to which will be the Net::SMTP object. After the block is finished, the Net::SMTP object will be automatically closed. Though passing a block is the preferred and cleaner method of using the SMTP interface, it's not appropriate in all situations.

 #!/usr/bin/env ruby
 require 'net/smtp'
 smtp = Net::SMTP.start(
  1. About.com
  2. Technology
  3. Ruby
  4. Tutorials
  5. Installation and Setup

©2014 About.com. All rights reserved.