Module: Sisimai::Lhost::AmazonSES

Defined in:
lib/sisimai/lhost/amazonses.rb

Overview

Sisimai::Lhost::AmazonSES decodes a bounce email which created by Amazon Simple Email Service aws.amazon.com/ses/. Methods in the module are called from only Sisimai::Message.

Constant Summary collapse

ReasonPair =
{
  "Suppressed"               => "suppressed",
  "OnAccountSuppressionList" => "suppressed",
  "General"                  => "onhold",
  "MailboxFull"              => "mailboxfull",
  "MessageTooLarge"          => "emailtoolarge",
  "ContentRejected"          => "contenterror",
  "AttachmentRejected"       => "securityerror",
}.freeze

Class Method Summary collapse

Class Method Details

.descriptionObject



214
# File 'lib/sisimai/lhost/amazonses.rb', line 214

def description; return 'Amazon SES(Sending): https://aws.amazon.com/ses/'; end

.inquire(mhead, mbody) ⇒ Hash, Nil

This method is abstract.

Decodes the bounce message from Amazon SES

Parameters:

  • mhead (Hash)

    Message headers of a bounce email

  • mbody (String)

    Message body of a bounce email

Returns:

  • (Hash)

    Bounce data list and message/rfc822 part

  • (Nil)

    it failed to decode or the arguments are missing



62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
# File 'lib/sisimai/lhost/amazonses.rb', line 62

def inquire(mhead, mbody)
  return nil if mbody.include?("{") == false
  return nil if mhead.has_key?("x-amz-sns-message-id") == false
  return nil if mhead["x-amz-sns-message-id"].empty?

  proceedsto = false
  sespayload = mbody
  while true
    # Remote the following string begins with "--"
    # --
    # If you wish to stop receiving notifications from this topic, please click or visit the link below to unsubscribe:
    # https://sns.us-west-2.amazonaws.com/unsubscribe.html?SubscriptionArn=arn:aws:sns:us-west-2:1...
    p1 = mbody.index("\n\n--\n")
    sespayload = mbody[0, p1] if p1
    sespayload = sespayload.gsub("!\n ", "")
    p2 = sespayload.index('"Message"')

    if p2
      # The JSON included in the email is a format like the following:
      # {
      #  "Type" : "Notification",
      #  "MessageId" : "02f86d9b-eecf-573d-b47d-3d1850750c30",
      #  "TopicArn" : "arn:aws:sns:us-west-2:123456789012:SES-EJ-B",
      #  "Message" : "{\"notificationType\"...
      sespayload = sespayload.gsub("\\", "")
      p3 = sespayload.index("{", p2 + 9)
      p4 = sespayload.index("\n", p2 + 9)
      sespayload = sespayload[p3, p4 - p3]
      sespayload = sespayload.delete_suffix(',').delete_suffix('"')
    end

    break if sespayload.include?("notificationType") == false
    break if sespayload.start_with?("{")             == false
    break if sespayload.end_with?("}")               == false
    proceedsto = true; break
  end
  return nil if proceedsto == false

  jsonobject = nil
  begin
    if RUBY_PLATFORM.start_with?("java")
      # java-based ruby environment like JRuby.
      require "jrjackson"
      jsonobject = JrJackson::Json.load(sespayload)
    else
      # Matz' Ruby Implementation
      require "oj"
      jsonobject = Oj.load(sespayload)
    end
  rescue StandardError => ce
    # Something wrong in decoding JSON
    warn " ***warning: Failed to decode JSON: #{ce.to_s}"
    return nil
  end
  return nil if jsonobject.has_key?("notificationType") == false

  require "sisimai/string"
  require "sisimai/rfc1123"
  require "sisimai/smtp/reply"
  require "sisimai/smtp/status"
  require "sisimai/smtp/command"
  dscontents = [Sisimai::Lhost.DELIVERYSTATUS]; v = dscontents[-1]
  recipients = 0  # (Integer) The number of 'Final-Recipient' header
  whatnotify = jsonobject["notificationType"][0, 1] || ""

  case whatnotify
  when "B"
    # "notificationType":"Bounce"
    p = jsonobject["bounce"]
    r = p["bounceType"] == "Permanent" ? "5" : "4"

    p["bouncedRecipients"].each do |e|
      # {"emailAddress":"neko@example.jp", "action":"failed", "status":"5.1.1", "diagnosticCode": "..."}
      if v["recipient"] != ""
        # There are multiple recipient addresses in the message body.
        dscontents << Sisimai::Lhost.DELIVERYSTATUS
        v = dscontents[-1]
      end
      v["recipient"] = e["emailAddress"]
      v["diagnosis"] = e["diagnosticCode"]
      v["command"]   = Sisimai::SMTP::Command.find(v["diagnosis"])
      v["action"]    = e["action"]
      v["status"]    = Sisimai::SMTP::Status.find(v["diagnosis"], r)
      v["replycode"] = Sisimai::SMTP::Reply.find(v["diagnosis"], v["status"])
      v["date"]      = p["timestamp"]
      v["lhost"]     = Sisimai::RFC1123.find(p["reportingMTA"])
      recipients += 1
    end

    ReasonPair.each_key do |f|
      #  Try to find the bounce reason by "bounceSubType"
      next if ReasonPair[f] != p["bounceSubType"]
      v["reason"] = f; break
    end
  when "C"
    # "notificationType":"Complaint"
    p = jsonobject["complaint"]
    p["complainedRecipients"].each do |e|
      # {"emailAddress":"neko@example.jp"}
      if v["recipient"] != ""
        # There are multiple recipient addresses in the message body.
        dscontents << Sisimai::Lhost.DELIVERYSTATUS
        v = dscontents[-1]
      end
      v["recipient"]    = e["emailAddress"]
      v["reason"]       = "feedback"
      v["feedbacktype"] = p["complaintFeedbackType"]
      v["date"]         = p["timestamp"]
      v["diagnosis"]    = sprintf('"feedbackid":"%s", "useragent":"%s"}', p["feedbackId"], p["userAgent"])
      recipients += 1
    end
  when "D"
    # "notificationType":"Delivery"
    p = jsonobject["delivery"]
    p["recipients"].each do |e|
      # {"recipients":["neko@example.jp"]}
      if v["recipient"] != ""
        # There are multiple recipient addresses in the message body.
        dscontents << Sisimai::Lhost.DELIVERYSTATUS
        v = dscontents[-1]
      end
      v["recipient"] = e
      v["reason"]    = "delivered"
      v["action"]    = "delivered"
      v["date"]      = p["timestamp"]
      v["lhost"]     = Sisimai::RFC1123.find(p["reportingMTA"])
      v["diagnosis"] = p["smtpResponse"]
      v["command"]   = Sisimai::SMTP::Command.find(v["diagnosis"])
      v["status"]    = Sisimai::SMTP::Status.find(v["diagnosis"], "2")
      v["replycode"] = Sisimai::SMTP::Reply.find(v["diagnosis"], "2")
      recipients += 1
    end
  else
    # Unknown "notificationType" value
    warn sprintf(" ***warning: There is no notificationType field or unknown type of notificationType field")
    return nil
  end
  return nil if recipients == 0

  # Date::Time.strptime() cannot parse "2016-11-25T01:49:01.000Z" format
  dscontents.each { |e| e["date"] = e["date"].sub("T", " ").sub(/[.]\d{3}Z/, "") }

  cv = ""
  jsonobject["mail"]["headers"].each do |e|
    cv += sprintf("%s: %s\n", e["name"], e["value"])
  end
  %w[date subject].each do |e|
    next if jsonobject["mail"]["commonHeaders"].has_key?(e) == false
    cv += sprintf("%s: %s\n", e.capitalize, jsonobject["mail"]["commonHeaders"][e])
  end
  return {"ds" => dscontents, "rfc822" => cv}
end