class LogTimer::Mailer

Handles sending of mails via smtp or local (mail-utils)

Attributes

from[RW]
smtp_password[RW]
smtp_port[RW]
smtp_server[RW]
smtp_user[RW]
to[RW]

Public Class Methods

new(options) click to toggle source
# File lib/log_timer/mailer.rb, line 8
def initialize(options)
  @options = options
end

Public Instance Methods

send(subject, body) click to toggle source
# File lib/log_timer/mailer.rb, line 12
def send(subject, body)
  if @options[:smtp_server] && !@options[:smtp_server].empty?
    send_mail_smtp(compose_message(subject, body))
  else
    send_mail_local(subject, body)
  end
end

Protected Instance Methods

compose_message(subject, body) click to toggle source
# File lib/log_timer/mailer.rb, line 22
    def compose_message(subject, body)
      to_addresses = [*@options[:to]].join(', ')
      message = <<EOD
From: Log Notifier <#{@options[:from]}>
To: <#{to_addresses}>
Subject: #{subject}

#{body}
EOD
      message
    end
from_domain() click to toggle source
# File lib/log_timer/mailer.rb, line 56
def from_domain
  @options[:from].split('@')[1]
end
send_mail_local(subject, body) click to toggle source
# File lib/log_timer/mailer.rb, line 45
def send_mail_local(subject, body)
  stdin, stdout, stderr, wait_thr = Open3.popen3("mail -s \"#{subject.gsub('"', '\"')}\" #{@options[:to].join(', ')}")
  stdin.puts body

  stdin.close  # stdin, stdout and stderr should be closed explicitly in this form.
  stdout.close
  stderr.close

  wait_thr.value == 0
end
send_mail_smtp(message) click to toggle source
# File lib/log_timer/mailer.rb, line 34
def send_mail_smtp(message)
  ::Net::SMTP.start(
      @options[:smtp_server],
      @options[:smtp_port],
      from_domain,
      @options[:smtp_user],
      @options[:smtp_password]) do |smtp|
    smtp.send_message message, @options[:from], @options[:to]
  end
end