Module: Capcode::Helpers

Defined in:
lib/capcode/render/email.rb

Instance Method Summary collapse

Instance Method Details

#render_email(f, _) ⇒ Object

:nodoc:



9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
# File 'lib/capcode/render/email.rb', line 9

def render_email( f, _ ) #:nodoc:
  if @smtp.nil?
    @smtp = { :server => "127.0.0.1", :port => 25 }.merge(Capcode::Configuration.options[:email] || {})
  end

  # Set SMTP info
  conf = Mail::Configuration.instance.defaults
  conf.smtp @smtp[:server], @smtp[:port]
  
  # Create mail
  mail = Mail.new()

  # Mail Header
  mail.from = f[:from]
  mail.subject = f[:subject] if f.has_key?(:subject)      
  [:to, :cc, :bcc].each do |t|
    next unless f.has_key?(t) and not f[t].nil?
    if f[t].class == Array
      mail[t] = f[t]
    else
      mail[t] = f[t].to_s.split( ',' ).map { |x| x.strip }
    end
  end
  mail.message_id = f[:message_id] if f.has_key?(:message_id)      
  
  # Mail Body
  if f[:body].class == String
    mail.body = f[:body]
  elsif f[:body].class == Hash
    if f[:body].has_key?(:html)
      mail.html_part = Mail::Part.new
      mail.html_part.content_type = f[:body][:html].delete(:content_type) { |_| 'text/html' }
      mail.html_part.body = render( f[:body][:html] )
    end
    if f[:body].has_key?(:text)
      mail.text_part = Mail::Part.new
      mail.text_part.body = render( f[:body][:text] )
    end        
  end
  
  # Mail Attachment
  if f.has_key?(:file)
    f[:file] = [f[:file]] unless f[:file].class == Array
    f[:file].each do |file|
      data = {}
      if file.class == Hash
        data[:filename] = file.delete(:filename) if file.has_key?(:filename)
        data[:mime_type] = file.delete(:mime_type) if file.has_key?(:mime_type)
        data[:data] = self.send(file[:data])
      else 
        data = { :data => render( :static => file, :exact_path => false ), :filename => File.basename(file) }
      end
      mail.add_file(data)
    end
  end

  begin
    mail.deliver!
    render f[:ok]
  rescue
    render f[:error]
  end
end