email.go 10.0 KB

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