refactor: optimize email
This commit is contained in:
2
main.go
2
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"
|
||||
)
|
||||
|
||||
@@ -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)
|
||||
|
||||
Reference in New Issue
Block a user