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



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

def address_list(field)
  field&.formatted
end

.attachments(mail) ⇒ Object



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

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



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

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



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

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



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

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



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

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

.single_address(field) ⇒ Object



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

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

.text_body(mail) ⇒ Object



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

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