Module: Pony

Defined in:
lib/pony.rb

Class Method Summary collapse

Class Method Details

.build_tmail(options) ⇒ Object



30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
# File 'lib/pony.rb', line 30

def self.build_tmail(options)
  mail = TMail::Mail.new
  mail.to = options[:to]
  mail.from = options[:from] || 'pony@unknown'
  mail.subject = options[:subject]
  mail.body = options[:body] || ""
  mail.set_content_type(options[:content_type] || 'text/plain')
  (options[:attachments] || []).each do |name, body|
    attachment = TMail::Mail.new
    attachment.transfer_encoding = "base64"
    attachment.body = Base64.encode64(body)
    # attachment.set_content_type # TODO: if necessary
    attachment.set_content_disposition "attachment", "filename" => name
    mail.parts.push attachment
  end
  mail
end

.mail(options) ⇒ Object

Raises:

  • (ArgumentError)


15
16
17
18
19
20
21
22
23
24
25
26
27
28
# File 'lib/pony.rb', line 15

def self.mail(options)
  raise(ArgumentError, ":to is required") unless options[:to]

  via = options.delete(:via)
  if via.nil?
    transport build_tmail(options)
  else
    if via_options.include?(via.to_s)
      send("transport_via_#{via}", build_tmail(options), options)
    else
      raise(ArgumentError, ":via must be either smtp or sendmail")
    end
  end
end

.sendmail_binaryObject



48
49
50
# File 'lib/pony.rb', line 48

def self.sendmail_binary
  @sendmail_binary ||= `which sendmail`.chomp
end

.transport(tmail) ⇒ Object



52
53
54
55
56
57
58
# File 'lib/pony.rb', line 52

def self.transport(tmail)
  if File.executable? sendmail_binary
    transport_via_sendmail(tmail)
  else
    transport_via_smtp(tmail)
  end
end

.transport_via_sendmail(tmail, options = {}) ⇒ Object



64
65
66
67
68
69
70
71
72
# File 'lib/pony.rb', line 64

def self.transport_via_sendmail(tmail, options={})
  IO.popen('-', 'w+') do |pipe|
    if pipe
      pipe.write(tmail.to_s)
    else
      exec(sendmail_binary, *tmail.to)
    end
  end
end

.transport_via_smtp(tmail, options = {:smtp => {}}) ⇒ Object



74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
# File 'lib/pony.rb', line 74

def self.transport_via_smtp(tmail, options={:smtp => {}})
  default_options = {:smtp => { :host => 'localhost', :port => '25', :domain => 'localhost.localdomain' }}
  o = default_options[:smtp].merge(options[:smtp])
  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 tmail.to_s, tmail.from, tmail.to
  smtp.finish
end

.via_optionsObject



60
61
62
# File 'lib/pony.rb', line 60

def self.via_options
  %w(sendmail smtp)
end