DZone Snippets is a public source code repository. Easily build up your personal collection of code snippets, categorize them with tags / keywords, and share them with the world

Snippets has posted 5883 posts at DZone. View Full User Profile

Ultra-simplistic Ruby SMTP Server

04.29.2007
| 13704 views |
  • submit to reddit
        You'll know if you need this, otherwise steer clear ;-)

require 'gserver'

class SMTPServer < GServer
  def serve(io)
    @data_mode = false
    puts "Connected"
    io.print "220 hello\r\n"
    loop do
      if IO.select([io], nil, nil, 0.1)
	      data = io.readpartial(4096)
	      puts ">>" + data
	      ok, op = process_line(data)
	      break unless ok
	      io.print op
      end
      break if io.closed?
    end
    io.print "221 bye\r\n"
    io.close
  end

  def process_line(line)
    if (line =~ /^(HELO|EHLO)/)
      return true, "220 and..?\r\n"
    end
    if (line =~ /^QUIT/)
      return false, "bye\r\n"
    end
    if (line =~ /^MAIL FROM\:/)
      return true, "220 OK\r\n"
    end
    if (line =~ /^RCPT TO\:/)
      return true, "220 OK\r\n"
    end
    if (line =~ /^DATA/)
      @data_mode = true
      return true, "354 Enter message, ending with \".\" on a line by itself\r\n"
    end
    if (@data_mode) && (line.chomp =~ /^.$/)
      @data_mode = false
      return true, "220 OK\r\n"
    end
    if @data_mode
      puts line 
      return true, ""
    else
      return true, "500 ERROR\r\n"
    end
  end
end

a = SMTPServer.new(1234)
a.start
a.join
    

Comments

Snippets Manager replied on Thu, 2010/03/11 - 4:38am

What exactly I have to do. I just run the script in super user mode. But I am not able to send the mail to my gmail account. Any idea. I used the above script as server.rb.This is my mail.rb code. msgstr = < To: some Subject: test message Date: Sat, 23 Jun 2001 16:26:43 +0900 Message-Id: This is a test message. END_OF_MESSAGE require 'net/smtp' smtp = Net::SMTP.start('127.0.0.1', 25) smtp.send_message msgstr, 'somebofy@some.com', 'tobuddy@something.com' smtp.finish Yes my email address are changed.. But even if i give correct mail address. I am not able to send.

Snippets Manager replied on Mon, 2009/02/16 - 2:32pm

Hi, Thank you very much for providing this very usefull example. There is however an error in the above code. @data_mode shoud be Thread.current["data_mode"] everywhere in the code. This is because this variable should be thread local. Thanks very much and keep up the great work! wim