Subject: [GSoC PATCH v7 2/2] send-email: finer-grained SMTP error handling

From: Zheng Yuting <[email-masked]>
Date: Sun, 23 Mar 2025 10:21:11 +0800

Code captured errors but did not process them further.
This treated all failures the same without distinguishing SMTP status.

Add a regex to extract status codes as defined in RFC 5321:

- For 4yz (transient errors), return 1 and allow retries.
- For 5yz (permanent errors), return 0 as failure.
- For unrecognized codes, return 1 as transient errors.
- For errors where the status code was not caught, return 1 as transient
errors.
- If no error and no result is returned, return 1 as a transient error.
- If no error occurs with result defined, return the authentication result.

Signed-off-by: Zheng Yuting <[email-masked]>
---
 git-send-email.perl | 35 ++++++++++++++++++++++++++++++++---
 1 file changed, 32 insertions(+), 3 deletions(-)

diff --git a/git-send-email.perl b/git-send-email.perl
index 0f05f55e50..e09a4a316f 100755
--- a/git-send-email.perl
+++ b/git-send-email.perl
@@ -1454,9 +1454,38 @@ sub smtp_auth_maybe {
 			$error = $@ || 'Unknown error';
 		};
 
-		# NOTE: SMTP status code handling will be added in a subsequent commit,
-		# return 1 when failed due to non-credential reasons
-		return $error ? 1 : ($result ? 1 : 0);
+		if ($error) {
+			# check if an error was captured
+			# parse SMTP status code from error message in:
+			# https://www.rfc-editor.org/rfc/rfc5321.html
+			if ($error =~ /\b(\d{3})\b/) {
+				my $status_code = $1;
+				if ($status_code =~ /^4/) {
+					# 4yz: Transient Negative Completion reply
+					warn "SMTP temporary error (status code $status_code): $error";
+					return 1;
+				} elsif ($status_code =~ /^5/) {
+					# 5yz: Permanent Negative Completion reply
+					warn "SMTP permanent error (status code $status_code): $error";
+					return 0;
+				} else {
+					# if no recognized status code is found, treat as transient error
+					warn "SMTP unknown error: $error. Treating as permanent failure.";
+					return 1;
+				}
+			} else {
+				# if no status code is found, treat as transient error
+				warn "SMTP generic error: $error";
+				return 1;
+			}
+		} elsif (!defined $result) {
+			# if no error and no result is returned, treat as transient error
+			warn "SMTP no result error: $error";
+		    return 1; 
+		}
+		else {
+			return $result ? 1 : 0;
+		}
 	});
 
 	return $auth;
-- 
2.49.0