: 
http://rubylearning.com/ http://rubylearning.com/satishtalim/tutorial.html http://rubylearning.com/download/downloads.html http://rubylearning.com/other/certification.html http://rubylearning.com/blog/ http://rubylearning.com/other/ruby_news.html http://rubylearning.com/other/testimonials.html http://rubylearning.com/jobs/ruby_jobs.html http://rubylearning.com/other/ruby_gurus.html http://rubylearning.com/satishtalim/services.html http://rubylearning.com/contact/contact.html http://rubylearning.com/satishtalim/about.html


SMTP class

Let's build a small SMTP client using the SMTP class in Ruby. For this, I am referring to Request for Comments (RFC's) 1869, 2554, 2821, 2822 and 3207. The program p070rubysmtp.rb is the SMTP client and the explanation follows.


# p070rubysmtp.rb

require 'net/smtp'

user_from = "satish@puneruby.com"

user_to = "ashish@puneruby.com"

the_email = "From: satish@puneruby.com\nSubject: Hello\n\nEmail by Ruby.\n\n"

# handling exceptions

begin

  Net::SMTP.start('auth.smtp.1and1.co.uk', 25, '1and1.co.uk', 'satish@puneruby.com', 'password', :login) do |smtpclient|

    smtpclient.send_message(the_email, user_from, user_to)

  end

rescue Exception => e

  print "Exception occured: " + e

end


Here's some explanation of the code:

  • The Net::SMTP library provides functionality to send internet mail via SMTP, the Simple Mail Transfer Protocol. This library does NOT provide functions to compose internet mails. You must create them by yourself
  • The line Net::SMTP.start creates a new Net::SMTP object, opens a TCP connection and connects to the server. 'auth.smtp.1and1.co.uk' is the IP address of your SMTP server and the port used is 25. Since we have called with a block, the newly-opened Net::SMTP object is yielded to the block, and automatically closed when the block finishes. The third argument is the domain name which you are on (the host to send mail from). The next three arguments are the login id, password and form of authentication used (here :login). SMTP authentication schemes are represented with symbols (:login, :plain, :cram_md). Any given SMTP server may support any or all of these schemes.
  • In the line smtpclient.send_message(the_email, user_from, user_to) the_email is the message to be sent. Single CR and LF found in the string, are converted to the CRLF pair. You cannot send a binary message with this method. the_email should include both the message headers and body. user_from is a String representing the source mail address. user_to is a String or Array of Strings, representing the destination mail address or addresses
  • The way we have used Net::SMTP.start it finishes the SMTP session and closes TCP connection
  • We have also used begin and rescue for Exception handling




Learning Ruby Navigation                                                                   <Socket Programming  | TOC  |  Web services>