class SMTP

This is the main class that performs the connection.

Public Class Methods

new(server:, sending_server: "mail.example.com", mail_from: "user@example.com", mail_rcpt_to:, mail_headers: nil, mail_subject: "This is a test message", mail_body: "This is a test message.\nRegards,\nraw_smtp" ) click to toggle source
  • server: server to attempt an SMTP connection to.

  • mail_from: sender, what to populate MAIL_FROM headers with.

  • mail_rcpt_to: recepient, what to populate RCPT_TO headers with.

  • mail_headers: custom headers. Need to be specified fully in a tabulated string format. Overrides all header parameters!

  • mail_subject: email subject to be inserted into headers.

  • mail_body: email body in a tabulated string format.

# File lib/raw_smtp/smtp.rb, line 21
  def initialize(server:,
                 sending_server: "mail.example.com",
                 mail_from: "user@example.com",
                 mail_rcpt_to:,
                 mail_headers: nil,
                 mail_subject: "This is a test message",
                 mail_body: "This is a test message.\nRegards,\nraw_smtp"
                )
    @server = server
    @sending_server = sending_server
    @mail_from = mail_from
    @mail_rcpt_to = mail_rcpt_to
    @mail_subject = mail_subject
    @mail_body = mail_body

    unless mail_headers
      @mail_headers = <<-EOH.gsub(/^\s+/, "")
      \tMIME-Version: 1.0
      \tMessage-ID:#{Digest::SHA2.hexdigest(Time.now.to_i.to_s)}@#{@sending_server}
      \tSubject: #{@mail_subject}
      \tFrom: #{@mail_from}
      \tTo: #{@mail_rcpt_to}
      \t
      EOH
    else
      @mail_headers = mail_headers
    end
  end

Public Instance Methods

connect!() click to toggle source
# File lib/raw_smtp/smtp.rb, line 50
def connect!
  puts "Trying to open an SMTP session..."
  connection = TCPSocket.new @server, 25

  mail_data_chunk = @mail_headers + @mail_body + "\n."

  protocol_queue = [
    "EHLO #{@sending_server}",
    "MAIL FROM:<#{@mail_from}>",
    "RCPT TO:<#{@mail_rcpt_to}>",
    "DATA",
    "#{mail_data_chunk}",
    "QUIT"
  ]

  while message = protocol_queue.shift
    connection.puts(message)
    puts message
    sleep 1
    puts connection.recv(2048)
  end

  puts "Session closed."
  connection.close
end