email.go 9.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331
  1. package email
  2. import (
  3. "context"
  4. "crypto/rand"
  5. "crypto/tls"
  6. "encoding/hex"
  7. "fmt"
  8. "mime"
  9. "net"
  10. "net/mail"
  11. "net/smtp"
  12. "strings"
  13. "time"
  14. "github.com/mhsanaei/3x-ui/v3/internal/web/service"
  15. )
  16. // EmailService sends email notifications via SMTP.
  17. type EmailService struct {
  18. settingService service.SettingService
  19. }
  20. // SMTPTestResult holds the result of an SMTP connection test.
  21. type SMTPTestResult struct {
  22. Success bool `json:"success"`
  23. Stage string `json:"stage"` // "connect" | "auth" | "send"
  24. Message string `json:"message"` // classified error message
  25. }
  26. // NewEmailService creates a new EmailService.
  27. func NewEmailService(settingService service.SettingService) *EmailService {
  28. return &EmailService{settingService: settingService}
  29. }
  30. // Send sends an HTML email to all configured recipients.
  31. func (s *EmailService) Send(subject, body string) error {
  32. host, err := s.settingService.GetSmtpHost()
  33. if err != nil || host == "" {
  34. return fmt.Errorf("smtp host not configured")
  35. }
  36. port, err := s.settingService.GetSmtpPort()
  37. if err != nil || port <= 0 {
  38. port = 587
  39. }
  40. username, _ := s.settingService.GetSmtpUsername()
  41. password, _ := s.settingService.GetSmtpPassword()
  42. fromAddr, _ := s.settingService.GetSmtpFrom()
  43. fromName, _ := s.settingService.GetSmtpFromName()
  44. toStr, _ := s.settingService.GetSmtpTo()
  45. encryptionType, _ := s.settingService.GetSmtpEncryptionType()
  46. from := fromAddr
  47. if from == "" {
  48. from = username
  49. }
  50. if from == "" {
  51. return fmt.Errorf("smtp from not configured")
  52. }
  53. recipients := parseRecipients(toStr)
  54. if len(recipients) == 0 {
  55. return fmt.Errorf("no recipients configured")
  56. }
  57. addr := net.JoinHostPort(host, fmt.Sprintf("%d", port))
  58. msg := buildMessage(from, fromName, recipients, subject, body)
  59. // Authenticate only when credentials are set. Go's PlainAuth refuses to run
  60. // over the unencrypted "none" transport, so an open relay must use nil auth.
  61. var auth smtp.Auth
  62. if username != "" && password != "" {
  63. auth = smtp.PlainAuth("", username, password, host)
  64. }
  65. // Wrap in a channel with timeout to prevent indefinite blocking
  66. type result struct{ err error }
  67. ch := make(chan result, 1)
  68. go func() {
  69. switch encryptionType {
  70. case "tls":
  71. ch <- result{s.sendWithTLS(addr, auth, from, recipients, msg, host)}
  72. case "starttls", "none":
  73. ch <- result{smtp.SendMail(addr, auth, from, recipients, msg)}
  74. default:
  75. ch <- result{fmt.Errorf("unknown SMTP encryption type: %s", encryptionType)}
  76. }
  77. }()
  78. select {
  79. case r := <-ch:
  80. return r.err
  81. case <-time.After(30 * time.Second):
  82. return fmt.Errorf("smtp connection timed out after 30s")
  83. }
  84. }
  85. // TestConnection tests SMTP connection stage by stage and sends a test email.
  86. func (s *EmailService) TestConnection() SMTPTestResult {
  87. host, err := s.settingService.GetSmtpHost()
  88. if err != nil || host == "" {
  89. return SMTPTestResult{false, "connect", "smtpHostNotConfigured"}
  90. }
  91. port, err := s.settingService.GetSmtpPort()
  92. if err != nil || port <= 0 {
  93. port = 587
  94. }
  95. username, _ := s.settingService.GetSmtpUsername()
  96. password, _ := s.settingService.GetSmtpPassword()
  97. fromAddr, _ := s.settingService.GetSmtpFrom()
  98. fromName, _ := s.settingService.GetSmtpFromName()
  99. toStr, _ := s.settingService.GetSmtpTo()
  100. encryptionType, _ := s.settingService.GetSmtpEncryptionType()
  101. from := fromAddr
  102. if from == "" {
  103. from = username
  104. }
  105. recipients := parseRecipients(toStr)
  106. if len(recipients) == 0 {
  107. return SMTPTestResult{false, "send", "smtpNoRecipients"}
  108. }
  109. addr := net.JoinHostPort(host, fmt.Sprintf("%d", port))
  110. // Stage 1: Connect
  111. var conn net.Conn
  112. dialer := &net.Dialer{Timeout: 5 * time.Second}
  113. switch encryptionType {
  114. case "tls":
  115. conn, err = (&tls.Dialer{NetDialer: dialer, Config: &tls.Config{
  116. ServerName: host,
  117. InsecureSkipVerify: false,
  118. }}).DialContext(context.Background(), "tcp", addr)
  119. default:
  120. conn, err = dialer.Dial("tcp", addr)
  121. }
  122. if err != nil {
  123. return SMTPTestResult{false, "connect", classifySMTPError(err)}
  124. }
  125. defer conn.Close()
  126. // Stage 2: Handshake + Auth
  127. client, err := smtp.NewClient(conn, host)
  128. if err != nil {
  129. return SMTPTestResult{false, "auth", classifySMTPError(err)}
  130. }
  131. defer client.Close()
  132. if err = client.Hello("localhost"); err != nil {
  133. return SMTPTestResult{false, "auth", classifySMTPError(err)}
  134. }
  135. // STARTTLS upgrade for non-TLS connections
  136. if encryptionType == "starttls" {
  137. if ok, _ := client.Extension("STARTTLS"); ok {
  138. if err = client.StartTLS(&tls.Config{ServerName: host}); err != nil {
  139. return SMTPTestResult{false, "auth", classifySMTPError(err)}
  140. }
  141. }
  142. }
  143. if username != "" && password != "" {
  144. auth := smtp.PlainAuth("", username, password, host)
  145. if err = client.Auth(auth); err != nil {
  146. return SMTPTestResult{false, "auth", classifySMTPError(err)}
  147. }
  148. }
  149. // Stage 3: Send test email
  150. if err = client.Mail(from); err != nil {
  151. return SMTPTestResult{false, "send", classifySMTPError(err)}
  152. }
  153. for _, r := range recipients {
  154. if err = client.Rcpt(r); err != nil {
  155. return SMTPTestResult{false, "send", classifySMTPError(err)}
  156. }
  157. }
  158. msg := buildMessage(from, fromName, recipients, "[3x-ui] Test email",
  159. `<html><body style="font-family:monospace;font-size:14px">
  160. <h2>Test email from 3x-ui</h2>
  161. <p>If you received this, SMTP is configured correctly.</p>
  162. </body></html>`)
  163. w, err := client.Data()
  164. if err != nil {
  165. return SMTPTestResult{false, "send", classifySMTPError(err)}
  166. }
  167. if _, err = w.Write(msg); err != nil {
  168. return SMTPTestResult{false, "send", classifySMTPError(err)}
  169. }
  170. if err = w.Close(); err != nil {
  171. return SMTPTestResult{false, "send", classifySMTPError(err)}
  172. }
  173. return SMTPTestResult{true, "send", "smtpTestSuccess"}
  174. }
  175. func (s *EmailService) sendWithTLS(addr string, auth smtp.Auth, from string, to []string, msg []byte, host string) error {
  176. // Dial with explicit timeout
  177. dialer := &net.Dialer{Timeout: 10 * time.Second}
  178. conn, err := (&tls.Dialer{NetDialer: dialer, Config: &tls.Config{
  179. ServerName: host,
  180. InsecureSkipVerify: false,
  181. }}).DialContext(context.Background(), "tcp", addr)
  182. if err != nil {
  183. return err
  184. }
  185. defer conn.Close()
  186. client, err := smtp.NewClient(conn, host)
  187. if err != nil {
  188. return err
  189. }
  190. defer client.Close()
  191. if err = client.Hello("localhost"); err != nil {
  192. return err
  193. }
  194. if auth != nil {
  195. if err = client.Auth(auth); err != nil {
  196. return err
  197. }
  198. }
  199. if err = client.Mail(from); err != nil {
  200. return err
  201. }
  202. for _, r := range to {
  203. if err = client.Rcpt(r); err != nil {
  204. return err
  205. }
  206. }
  207. w, err := client.Data()
  208. if err != nil {
  209. return err
  210. }
  211. if _, err = w.Write(msg); err != nil {
  212. return err
  213. }
  214. return w.Close()
  215. }
  216. // SendTest sends a test email and returns any error with detail.
  217. func (s *EmailService) SendTest() error {
  218. return s.Send(
  219. "[3x-ui] Test email",
  220. `<html><body style="font-family:monospace;font-size:14px">
  221. <h2>Test email from 3x-ui</h2>
  222. <p>If you received this, SMTP is configured correctly.</p>
  223. </body></html>`,
  224. )
  225. }
  226. // classifySMTPError maps raw SMTP errors to human-readable messages.
  227. func classifySMTPError(err error) string {
  228. msg := err.Error()
  229. msgLower := strings.ToLower(msg)
  230. switch {
  231. case strings.Contains(msg, "535") || strings.Contains(msgLower, "authentication"):
  232. return "pages.settings.smtpErrorAuth"
  233. case strings.Contains(msg, "534") || strings.Contains(msgLower, "starttls"):
  234. return "pages.settings.smtpErrorStarttls"
  235. case strings.Contains(msg, "465") || strings.Contains(msgLower, "tls"):
  236. return "pages.settings.smtpErrorTls"
  237. case strings.Contains(msgLower, "connection refused") || strings.Contains(msgLower, "dial"):
  238. return "pages.settings.smtpErrorRefused"
  239. case strings.Contains(msgLower, "timeout"):
  240. return "pages.settings.smtpErrorTimeout"
  241. case strings.Contains(msg, "550") || strings.Contains(msgLower, "relay"):
  242. return "pages.settings.smtpErrorRelay"
  243. case strings.Contains(msgLower, "eof"):
  244. return "pages.settings.smtpErrorEof"
  245. default:
  246. return fmt.Sprintf("pages.settings.smtpErrorUnknown: %s", msg)
  247. }
  248. }
  249. func parseRecipients(toStr string) []string {
  250. if toStr == "" {
  251. return nil
  252. }
  253. var out []string
  254. for s := range strings.SplitSeq(toStr, ",") {
  255. s = strings.TrimSpace(s)
  256. if s != "" {
  257. out = append(out, s)
  258. }
  259. }
  260. return out
  261. }
  262. // buildMessage assembles an RFC 5322 message. It emits the two mandatory
  263. // header fields (Date, From) plus Message-ID, so strict receivers such as Gmail
  264. // accept it and spam filters do not penalize a missing date or message id. The
  265. // From header is a proper name-addr ("Name" <addr>) via net/mail, and a
  266. // non-ASCII subject is RFC 2047 encoded.
  267. // headerSanitizer drops CR/LF so a crafted address or name cannot inject extra
  268. // header lines. Configured addresses are already validated at save time
  269. // (entity.AllSetting.CheckValid), this is defense in depth for buildMessage.
  270. var headerSanitizer = strings.NewReplacer("\r", "", "\n", "")
  271. func buildMessage(fromAddr, fromName string, to []string, subject, body string) []byte {
  272. fromAddr = headerSanitizer.Replace(fromAddr)
  273. fromName = headerSanitizer.Replace(fromName)
  274. from := (&mail.Address{Name: fromName, Address: fromAddr}).String()
  275. domain := "localhost"
  276. if at := strings.LastIndex(fromAddr, "@"); at >= 0 && at+1 < len(fromAddr) {
  277. domain = fromAddr[at+1:]
  278. }
  279. var token [16]byte
  280. _, _ = rand.Read(token[:])
  281. messageID := fmt.Sprintf("<%s@%s>", hex.EncodeToString(token[:]), domain)
  282. var msg strings.Builder
  283. fmt.Fprintf(&msg, "Date: %s\r\n", time.Now().Format(time.RFC1123Z))
  284. fmt.Fprintf(&msg, "From: %s\r\n", from)
  285. fmt.Fprintf(&msg, "To: %s\r\n", strings.Join(to, ", "))
  286. fmt.Fprintf(&msg, "Message-ID: %s\r\n", messageID)
  287. fmt.Fprintf(&msg, "Subject: %s\r\n", mime.QEncoding.Encode("utf-8", subject))
  288. msg.WriteString("MIME-Version: 1.0\r\n")
  289. msg.WriteString("Content-Type: text/html; charset=utf-8\r\n")
  290. msg.WriteString("\r\n")
  291. msg.WriteString(body)
  292. return []byte(msg.String())
  293. }