Class: MultiMail::Sender::SendGrid

Inherits:
Object
  • Object
show all
Includes:
Base
Defined in:
lib/multi_mail/sendgrid/sender.rb

Overview

SendGrid's outgoing mail sender.

Instance Attribute Summary

Attributes included from Base

#settings, #tracking

Instance Method Summary collapse

Methods included from Base

included

Constructor Details

#initialize(options = {}) ⇒ SendGrid

Initializes a SendGrid outgoing email sender.

Parameters:

  • options (Hash) (defaults to: {})

    required and optional arguments

Options Hash (options):

  • :api_user (String)

    a SendGrid API user

  • :api_key (String)

    a SendGrid API key

  • the (Hash, String)

    X-SMTPAPI SendGrid header

See Also:



17
18
19
20
21
22
# File 'lib/multi_mail/sendgrid/sender.rb', line 17

def initialize(options = {})
  super
  if Hash === settings[:'x-smtpapi']
    settings[:'x-smtpapi'] = JSON.dump(settings[:'x-smtpapi'])
  end
end

Instance Method Details

#deliver!(mail) ⇒ Object

Delivers a message via the SendGrid API.

Parameters:

See Also:



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
# File 'lib/multi_mail/sendgrid/sender.rb', line 28

def deliver!(mail)
  parameters = settings.dup
  parameters.delete(:return_response)
  message = MultiMail::Message::SendGrid.new(mail).to_sendgrid_hash.merge(parameters)

  connection = Faraday.new do |conn|
    conn.request :multipart
    conn.request :url_encoded
    conn.adapter Faraday.default_adapter
  end

  response = connection.post('https://sendgrid.com/api/mail.send.json', message)

  body = JSON.load(response.body)

  unless response.status == 200
    if body['message'] == 'error'
      case body['errors']
      when ['Bad username / password']
        raise InvalidAPIKey, body['errors'].first
      when ['Empty from email address (required)']
        raise MissingSender, body['errors'].first
      when ['Missing destination email']
        raise MissingRecipients, body['errors'].first
      when ['Missing subject']
        raise MissingSubject, body['errors'].first
      when ['Missing email body']
        raise MissingBody, body['errors'].first
      else
        raise body['errors'].join
      end
    else
      raise body['errors'].join
    end
  end

  if settings[:return_response]
    body
  else
    self
  end
end