Module: Cloudflare::EmailService::Rails::MessageMapping

Defined in:
lib/cloudflare/email_service/rails.rb

Overview

Converts an ActionMailer-built Mail::Message into the keyword arguments accepted by Message#initialize.

Constant Summary collapse

PASSTHROUGH_HEADERS =

Forwarded headers: anything custom (X-*) plus threading headers. The structural headers (From/To/Subject/Content-Type/…) are mapped above.

%w[in-reply-to references].freeze

Class Method Summary collapse

Class Method Details

.address_list(field) ⇒ Object



48
49
50
# File 'lib/cloudflare/email_service/rails.rb', line 48

def address_list(field)
  field&.formatted
end

.attachments(mail) ⇒ Object



70
71
72
73
74
75
76
77
78
79
80
81
# File 'lib/cloudflare/email_service/rails.rb', line 70

def attachments(mail)
  return nil if mail.attachments.empty?

  mail.attachments.map do |part|
    {
      content: [part.body.decoded].pack("m0"),
      filename: part.filename,
      type: part.mime_type,
      disposition: part.inline? ? "inline" : "attachment",
    }
  end
end

.call(mail) ⇒ Object



29
30
31
32
33
34
35
36
37
38
39
40
41
42
# File 'lib/cloudflare/email_service/rails.rb', line 29

def call(mail)
  {
    from: single_address(mail[:from]),
    to: address_list(mail[:to]),
    cc: address_list(mail[:cc]),
    bcc: address_list(mail[:bcc]),
    reply_to: single_address(mail[:reply_to]),
    subject: mail.subject,
    text: text_body(mail),
    html: html_body(mail),
    attachments: attachments(mail),
    headers: custom_headers(mail),
  }
end

.custom_headers(mail) ⇒ Object



87
88
89
90
91
92
93
94
95
96
# File 'lib/cloudflare/email_service/rails.rb', line 87

def custom_headers(mail)
  headers = {}
  mail.header.fields.each do |field|
    name = field.name.to_s
    forwardable = name.downcase.start_with?("x-") ||
                  PASSTHROUGH_HEADERS.include?(name.downcase)
    headers[name] = field.value if forwardable
  end
  headers.empty? ? nil : headers
end

.html_body(mail) ⇒ Object



59
60
61
62
63
64
# File 'lib/cloudflare/email_service/rails.rb', line 59

def html_body(mail)
  return mail.html_part.decoded if mail.html_part
  return nil unless mail.mime_type == "text/html"

  presence(mail.body.decoded)
end

.presence(string) ⇒ Object



66
67
68
# File 'lib/cloudflare/email_service/rails.rb', line 66

def presence(string)
  string.nil? || string.empty? ? nil : string
end

.single_address(field) ⇒ Object



44
45
46
# File 'lib/cloudflare/email_service/rails.rb', line 44

def single_address(field)
  field&.formatted&.first
end

.text_body(mail) ⇒ Object



52
53
54
55
56
57
# File 'lib/cloudflare/email_service/rails.rb', line 52

def text_body(mail)
  return mail.text_part.decoded if mail.text_part
  return nil if mail.multipart? || mail.mime_type == "text/html"

  presence(mail.body.decoded)
end