FIX: No method error in WebhooksController#sendgrid (#31495)

When an email is sent by sendgrid to an email address with an invalid
host, the webhook payload does not contain the "status" field:

```
[
  {
    "bounce_classification": "Unclassified",
    "email": "noemail@this.does.not.exist.tld",
    "event": "bounce",
    "reason": "unable to get mx info: failed to get IPs from PTR record: lookup <nil>: unrecognized address",
    "sg_event_id": "Ym91bmNlLTQtNTA0ODUxOTUtZXVvMmlLeGRTYXlQRjRZRTQtLUk3QS0w",
    "sg_message_id": "euo2iKxdSayPF4YE4--I7A.recvd-5f54b5d587-pczjm-1-67BADEEA-6.0",
    "smtp-id": "<870b3a2a-160c-4fc8-bc9a-bd0d5b943b81@forum.umbraco.com>",
    "timestamp": 1740300320,
    "tls": 0,
    "type": "blocked"
  }
]
```

When the `status` field is missing, it results in a `NoMethodError
(undefined method `[]' for nil:NilClass)`
error in the controller method. In this commit, we will specifically
handle the webhook event from sendgrid when the email address's domain
is invalid.

Co-Authored-By: @nul800sebastiaan
This commit is contained in:
Alan Guo Xiang Tan
2025-02-25 13:08:59 +08:00
committed by GitHub
parent b02e87b8c4
commit 209d289772
2 changed files with 30 additions and 5 deletions

View File

@ -25,7 +25,12 @@ class WebhooksController < ActionController::Base
message_id = Email::MessageIdService.message_id_clean((event["smtp-id"] || ""))
to_address = event["email"]
error_code = event["status"]
if event["event"] == "bounce"
# Sendgrid does not provide status field for emails that can't be delivered due to the recipient's server not existing
# so we set the error code to 5.1.2 which translates to permanent failure bad destination system address.
error_code = "5.1.2" if !error_code && event["type"] == "blocked"
if error_code[Email::SMTP_STATUS_TRANSIENT_FAILURE]
process_bounce(message_id, to_address, SiteSetting.soft_bounce_score, error_code)
else