From 9876169c843a65a4e222f0e7b8b3260a0e5d6a9b Mon Sep 17 00:00:00 2001 From: yoge Date: Fri, 27 Mar 2026 01:23:01 +0800 Subject: [PATCH] refactor: optimize email --- main.go | 2 +- pkg/email/email.go | 22 ++++++++++++++-------- 2 files changed, 15 insertions(+), 9 deletions(-) diff --git a/main.go b/main.go index 391cc68..e487969 100644 --- a/main.go +++ b/main.go @@ -16,9 +16,9 @@ import ( "gitea.com/texpixel/document_ai/internal/storage/dao" "gitea.com/texpixel/document_ai/pkg/common" "gitea.com/texpixel/document_ai/pkg/cors" + "gitea.com/texpixel/document_ai/pkg/email" "gitea.com/texpixel/document_ai/pkg/log" "gitea.com/texpixel/document_ai/pkg/middleware" - "gitea.com/texpixel/document_ai/pkg/email" "gitea.com/texpixel/document_ai/pkg/sms" "github.com/gin-gonic/gin" ) diff --git a/pkg/email/email.go b/pkg/email/email.go index 919e69f..a805cd6 100644 --- a/pkg/email/email.go +++ b/pkg/email/email.go @@ -6,9 +6,12 @@ import ( "crypto/tls" "encoding/json" "fmt" + "io" "net/http" + "net/mail" "net/smtp" "regexp" + "strings" "sync" "gitea.com/texpixel/document_ai/config" @@ -36,17 +39,18 @@ func InitEmailClient() *Client { // Send routes the email to the appropriate provider based on the recipient domain. func Send(ctx context.Context, to, subject, body string) error { + if client == nil { + return fmt.Errorf("email client not initialized, call InitEmailClient first") + } return client.Send(ctx, to, subject, body) } func (c *Client) Send(ctx context.Context, to, subject, body string) error { - atIdx := len(to) - 1 - for i, ch := range to { - if ch == '@' { - atIdx = i - } + if _, err := mail.ParseAddress(to); err != nil { + return fmt.Errorf("invalid email address %q: %w", to, err) } - domain := to[atIdx:] + + domain := to[strings.LastIndex(to, "@")+1:] if chineseDomainRe.MatchString(domain) { return c.sendViaAliyunSMTP(ctx, to, subject, body) } @@ -66,6 +70,7 @@ func (c *Client) sendViaAliyunSMTP(ctx context.Context, to, subject, body string smtpClient, err := smtp.NewClient(conn, cfg.Host) if err != nil { + conn.Close() log.Error(ctx, "func", "sendViaAliyunSMTP", "msg", "smtp new client failed", "error", err) return err } @@ -133,8 +138,9 @@ func (c *Client) sendViaResend(ctx context.Context, to, subject, body string) er defer resp.Body.Close() if resp.StatusCode != http.StatusOK && resp.StatusCode != http.StatusCreated { - log.Error(ctx, "func", "sendViaResend", "msg", "resend api returned non-2xx", "status", resp.StatusCode, "to", to) - return fmt.Errorf("resend api returned status: %d", resp.StatusCode) + respBody, _ := io.ReadAll(io.LimitReader(resp.Body, 1024)) + log.Error(ctx, "func", "sendViaResend", "msg", "resend api returned non-2xx", "status", resp.StatusCode, "to", to, "body", string(respBody)) + return fmt.Errorf("resend api returned status %d: %s", resp.StatusCode, string(respBody)) } log.Info(ctx, "func", "sendViaResend", "msg", "email sent via resend", "to", to)