Class: Resend::Mailer

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

Overview

Mailer class used by railtie

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(config) ⇒ Mailer

Returns a new instance of Mailer.

Raises:

  • (Resend::ResendError)


10
11
12
13
14
15
# File 'lib/resend/mailer.rb', line 10

def initialize(config)
  @config = config
  raise Resend::ResendError.new("Config requires api_key", @config) unless @config.key?(:api_key)

  @settings = { return_response: true } # avoids NilError exception
end

Instance Attribute Details

#configObject

Returns the value of attribute config.



8
9
10
# File 'lib/resend/mailer.rb', line 8

def config
  @config
end

#settingsObject

Returns the value of attribute settings.



8
9
10
# File 'lib/resend/mailer.rb', line 8

def settings
  @settings
end

Instance Method Details

#build_resend_params(mail) ⇒ Object



24
25
26
27
28
29
30
31
32
33
34
# File 'lib/resend/mailer.rb', line 24

def build_resend_params(mail)
  params = {
    from: get_from(mail.from),
    to: mail.to,
    subject: mail.subject
  }
  params.merge!(get_addons(mail))
  params[:attachments] = get_attachments(mail) if mail.attachments.present?
  params.merge!(get_contents(mail))
  params
end

#deliver!(mail) ⇒ Object



17
18
19
20
21
22
# File 'lib/resend/mailer.rb', line 17

def deliver!(mail)
  params = build_resend_params(mail)
  resp = Resend::Emails.send(params)
  mail.message_id = resp[:id] if resp[:error].nil?
  resp
end

#get_addons(mail) ⇒ Object



36
37
38
39
40
41
42
# File 'lib/resend/mailer.rb', line 36

def get_addons(mail)
  params = {}
  params[:cc] = mail.cc if mail.cc.present?
  params[:bcc] = mail.bcc if mail.bcc.present?
  params[:reply_to] = mail.reply_to if mail.reply_to.present?
  params
end

#get_attachments(mail) ⇒ Object



64
65
66
67
68
69
70
71
72
73
74
# File 'lib/resend/mailer.rb', line 64

def get_attachments(mail)
  attachments = []
  mail.attachments.each do |part|
    attachment = {
      filename: part.filename,
      content: part.body.decoded.bytes
    }
    attachments.append(attachment)
  end
  attachments
end

#get_contents(mail) ⇒ Object



44
45
46
47
48
49
50
51
52
53
54
55
56
# File 'lib/resend/mailer.rb', line 44

def get_contents(mail)
  params = {}
  case mail.mime_type
  when "text/plain"
    params[:text] = mail.body.decoded
  when "text/html"
    params[:html] = mail.body.decoded
  when "multipart/alternative", "multipart/mixed", "multipart/related"
    params[:text] = mail.text_part.decoded if mail.text_part
    params[:html] = mail.html_part.decoded if mail.html_part
  end
  params
end

#get_from(input) ⇒ Object



58
59
60
61
62
# File 'lib/resend/mailer.rb', line 58

def get_from(input)
  return input.first if input.is_a? Array

  input
end