Class: SendGrid::TemplateMailer

Inherits:
Object
  • Object
show all
Defined in:
lib/sendgrid/template_mailer.rb

Instance Method Summary collapse

Constructor Details

#initialize(client, template, recipients = []) ⇒ TemplateMailer

This class is responsible for coordinating the responsibilities

of various models in the gem.

It makes use of the Recipient, Template and Mail models to create

a single work flow, an example might look like:

users = User.where(email: [‘[email protected]’, ‘[email protected]’])

recipients = []

users.each do |user|

recipient = SendGrid::Recipient.new(user.email)
recipient.add_substitution('first_name', user.first_name)
recipient.add_substitution('city', user.city)

recipients << recipient

end

template = SendGrid::Template.new(‘MY_TEMPLATE_ID’)

client = SendGrid::Client.new(api_user: my_user, api_key: my_key)

mail_defaults =

from: '[email protected]',
html: '<h1>I like email</h1>',
text: 'I like email',
subject: 'Email is great',

mailer = SendGrid::TemplateMailer.new(client, template, recipients) mailer.mail(mail_defaults)

Raises:



38
39
40
41
42
43
44
45
46
47
48
49
50
# File 'lib/sendgrid/template_mailer.rb', line 38

def initialize(client, template, recipients = [])
  @client = client
  @template = template
  @recipients = recipients

  raise InvalidClient, 'Client must be present' if @client.nil?
  raise InvalidTemplate, 'Template must be present' if @template.nil?
  raise InvalidRecipients, 'Recipients may not be empty' if @recipients.empty?

  @recipients.each do |recipient|
    @template.add_recipient(recipient)
  end
end

Instance Method Details

#mail(params = {}) ⇒ Object



52
53
54
55
56
57
# File 'lib/sendgrid/template_mailer.rb', line 52

def mail(params = {})
  mail = Mail.new(params)

  mail.template = @template
  @client.send(mail.to_h)
end