email.go 8.1 KB

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