Class: GmailMailer::Mailer

Inherits:
Object
  • Object
show all
Defined in:
lib/gmail-mailer.rb

Instance Method Summary collapse

Constructor Details

#initialize(credentials) ⇒ Mailer

Returns a new instance of Mailer.



13
14
15
16
17
18
19
20
# File 'lib/gmail-mailer.rb', line 13

def initialize(credentials)
  begin
    validate_credentials(credentials)
  rescue
    raise
  end
  @email_credentials = credentials
end

Instance Method Details

#send(message) ⇒ Object



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
# File 'lib/gmail-mailer.rb', line 22

def send(message)
  mail = Mail.new do
    to message.to
    subject message.subject
    body message.body
  end
  if(!message.attachments.empty?)
    message.attachments.each do |attachment|
      mail.add_file(attachment)
    end
  end

  retry_attempts = 0

  begin
    send_smtp(mail)
  rescue => message
    puts "Error occured attempting to send mail => #{message}"

    raise message if(retry_attempts > MAX_RETRY)
    puts "Retry: #{retry_attempts+1}/#{MAX_RETRY+1}"
    retry_attempts = retry_attempts.succ
    retry
  end
end

#send_smtp(mail) ⇒ Object

Use gmail_xoauth to send email



49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
# File 'lib/gmail-mailer.rb', line 49

def send_smtp(mail)
  smtp = Net::SMTP.new(SMTP_SERVER, SMTP_PORT)
  smtp.enable_starttls_auto
  secret = {
    :consumer_key => SMTP_CONSUMER_KEY, 
    :consumer_secret => SMTP_CONSUMER_SECRET,
    :token => @email_credentials[:smtp_oauth_token],
    :token_secret => @email_credentials[:smtp_oauth_token_secret]
  }
  smtp.start(SMTP_HOST, @email_credentials[:email], secret, :xoauth) do |session|
    print "Sending message..."
    session.send_message(mail.encoded, mail.from_addrs.first, mail.destinations)
    puts ".sent!"
  end
end

#validate_credentials(creds) ⇒ Object

Raises:

  • (ArgumentError)


65
66
67
68
69
70
71
72
# File 'lib/gmail-mailer.rb', line 65

def validate_credentials(creds)
  msg = "ERROR: Email credentials are invalid:"
  raise ArgumentError, "#{msg} The credentials you have posted are nil" if creds.nil?
  raise ArgumentError, "#{msg} You must provide a smtp_oauth_token value!" if !creds.key?:smtp_oauth_token or creds[:smtp_oauth_token].nil? or creds[:smtp_oauth_token].empty?
  raise ArgumentError, "#{msg} You must provide a smtp_oauth_token_secret value!" if !creds.key?:smtp_oauth_token_secret or creds[:smtp_oauth_token_secret].nil? or creds[:smtp_oauth_token_secret].empty?
  raise ArgumentError, "#{msg} You must provide an email value" if !creds.key?:email or creds[:email].nil? or creds[:email].empty?
  return nil 
end