1. Home
  2. Computing & Technology
  3. Ruby

How to Send Email with Ruby

By , About.com Guide

4 of 5

Using Data Streams

The following example uses the data stream to compose a message. The data stream is a way of appending data to the end of a Ruby file and reading it using the DATA IO object. The DATA IO object is just like any of the other IO objects such as STDIN, STDOUT or an object returned by File.open. Calling DATA.read will read everything after the __END__ keyword into a string.

#!/usr/bin/env ruby
require 'net/smtp'

Net::SMTP.start(
  'mail.isp.com',
  25,
  'isp.com'
) do|smtp|

  message = DATA.read
  smtp.send_message(
    message,
    'username@isp.com',
    'username@other-isp.com'
  )
  smtp.finish

end

__END__
From: username@isp.com
To: username@other-isp.com
Subject: This is a message sent by Ruby!

This is the body of the message.
It can be as long as you like.
Explore Ruby
About.com Special Features

The Best Web Trends of the Decade

A look back at the best innovations, ideas and technologies over the last 10 years, More >

Family Tech Center

Stay connected and entertained with reviews on tips on the latest HDTVs, cellphones and more. More >

  1. Home
  2. Computing & Technology
  3. Ruby
  4. Tasks & Scripts
  5. Using Data Streams

©2009 About.com, a part of The New York Times Company.

All rights reserved.