Sha256: 7d0b5b04a0010862ebe26004ee8ba3d4ab8fb7b6b578e3d91acf53f4d6b09778

Contents?: true

Size: 1.65 KB

Versions: 1

Compression:

Stored size: 1.65 KB

Contents

require 'net/smtp'
begin; require 'smtp_tls'; rescue LoadError; end
require_relative '../ext/mimetic'

module PonyExpress
  TRANSPORTS = [ :smtp, :sendmail ]
  DEFAULT_SMTP_OPTIONS = { :host => 'localhost', :port => '25', :domain => 'localhost.localdomain' }

  Mimetic.load_mime_types File.dirname(__FILE__) + "/../mime.types"

  def self.build options
    # TODO validation.
    Mimetic.build(options)
  end

  def self.mail options
    via = (options.delete(:via) || :smtp).to_sym
    via_options = options.delete(:via_options) || {}

    if TRANSPORTS.include? via
      case via
      when :sendmail then transport_via_sendmail build(options), via_options
      when :smtp     then transport_via_smtp build(options), options[:from], options[:to], via_options
      end
    else
      raise ArgumentError, ":via can be one of #{TRANSPORTS}"
    end
  end

  private

  def self.sendmail_binary
    sendmail = `which sendmail`.chomp
    sendmail.empty? ? '/usr/sbin/sendmail' : sendmail
  end

  def self.transport_via_sendmail content, options={}
    IO.popen('-', 'w+') do |pipe|
      if pipe
        pipe.write(content)
      else
        exec(sendmail_binary, "-t")
      end
    end
  end

  def self.transport_via_smtp content, from, to, options={}
    o = DEFAULT_SMTP_OPTIONS.merge(options)
    smtp = Net::SMTP.new(o[:host], o[:port])
    if o[:tls]
      raise "You may need: gem install smtp_tls" unless smtp.respond_to?(:enable_starttls)
      smtp.enable_starttls
    end
    if o.include?(:auth)
      smtp.start(o[:domain], o[:user], o[:password], o[:auth])
    else
      smtp.start(o[:domain])
    end
    smtp.send_message content, from, to
    smtp.finish
  end

end

Version data entries

1 entries across 1 versions & 1 rubygems

Version Path
pony-express-0.5.0 lib/pony-express.rb