server.go 6.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285
  1. package smtpserver
  2. import (
  3. "crypto/tls"
  4. "errors"
  5. "fmt"
  6. "github.com/SongZihuan/web-watcher/src/config"
  7. "github.com/SongZihuan/web-watcher/src/utils"
  8. "gopkg.in/gomail.v2"
  9. "net"
  10. "net/mail"
  11. "net/smtp"
  12. "os"
  13. "strings"
  14. "sync"
  15. "time"
  16. )
  17. var smtpAddress string = ""
  18. var smtpUser string = ""
  19. var smtpPassword string = ""
  20. var smtpRecipient []*mail.Address
  21. var once sync.Once
  22. func InitSmtp() (err error) {
  23. once.Do(func() {
  24. recipientList := config.GetConfig().SMTP.Recipient
  25. smtpAddress = config.GetConfig().SMTP.Address
  26. smtpUser = config.GetConfig().SMTP.User
  27. smtpPassword = config.GetConfig().SMTP.Password
  28. smtpRecipient = make([]*mail.Address, 0, len(recipientList))
  29. if !config.IsReady() {
  30. panic("config is not ready")
  31. } else if smtpAddress == "" || smtpUser == "" {
  32. return
  33. } else if len(recipientList) == 0 {
  34. err = fmt.Errorf("not smt recopient")
  35. return
  36. }
  37. for _, rec := range recipientList {
  38. addr, err := mail.ParseAddress(strings.TrimSpace(rec))
  39. if err != nil {
  40. fmt.Printf("%s parser failled, ignore\n", rec)
  41. continue
  42. }
  43. if !utils.IsValidEmail(addr.Address) {
  44. fmt.Printf("%s is not a valid email, ignore\n", addr.Address)
  45. continue
  46. }
  47. smtpRecipient = append(smtpRecipient, addr)
  48. }
  49. if len(smtpRecipient) == 0 {
  50. err = fmt.Errorf("not any valid email address to be self recipient")
  51. return
  52. }
  53. })
  54. return err
  55. }
  56. func Send(subject string, msg string) error {
  57. if !config.IsReady() {
  58. panic("config is not ready")
  59. } else if smtpAddress == "" || smtpUser == "" {
  60. return nil
  61. }
  62. subject = fmt.Sprintf("【%s 消息提醒】 %s", config.GetConfig().SystemName, subject)
  63. now := time.Now()
  64. err := _sendTo(subject, msg, nil, nil, smtpRecipient, "", now)
  65. if err != nil {
  66. return err
  67. }
  68. return nil
  69. }
  70. func _sendTo(subject string, msg string, fromAddr *mail.Address, replyToAddr *mail.Address, toAddr []*mail.Address, messageID string, t time.Time) (err error) {
  71. if smtpAddress == "" || smtpUser == "" {
  72. return nil
  73. }
  74. defer func() {
  75. r := recover()
  76. if r != nil && err == nil {
  77. if _err, ok := r.(error); ok {
  78. err = _err
  79. } else {
  80. err = fmt.Errorf("panic: %v", r)
  81. }
  82. }
  83. }()
  84. sender := smtpUser
  85. if fromAddr == nil {
  86. fromAddr = &mail.Address{
  87. Name: config.GetConfig().SystemName,
  88. Address: smtpUser,
  89. }
  90. }
  91. if replyToAddr == nil {
  92. replyToAddr = &mail.Address{
  93. Name: fromAddr.Name,
  94. Address: fromAddr.Address,
  95. }
  96. }
  97. const missingPort = "missing port in address"
  98. host, port, err := net.SplitHostPort(smtpAddress)
  99. var addrErr *net.AddrError
  100. if errors.As(err, &addrErr) {
  101. if addrErr.Err == missingPort {
  102. host = smtpAddress
  103. port = "25"
  104. } else {
  105. return err
  106. }
  107. } else if err != nil {
  108. return err
  109. }
  110. tlsconfig := &tls.Config{
  111. ServerName: host,
  112. InsecureSkipVerify: false,
  113. }
  114. conn, err := net.Dial("tcp", net.JoinHostPort(host, port))
  115. if err != nil {
  116. return err
  117. }
  118. defer func() {
  119. _ = conn.Close()
  120. }()
  121. isSecureConn := false
  122. _conn := tls.Client(conn, tlsconfig)
  123. err = _conn.Handshake()
  124. if err == nil {
  125. conn = _conn
  126. isSecureConn = true
  127. }
  128. smtpClient, err := smtp.NewClient(conn, host)
  129. if err != nil {
  130. return fmt.Errorf("new smtp client: %v", err)
  131. }
  132. defer func() {
  133. _ = smtpClient.Quit()
  134. smtpClient = nil
  135. }()
  136. hostname, err := os.Hostname()
  137. if err != nil {
  138. return err
  139. }
  140. if err = smtpClient.Hello(hostname); err != nil {
  141. return fmt.Errorf("hello: %v", err)
  142. }
  143. // If not using SMTPS, always use STARTTLS if available
  144. hasStartTLS, _ := smtpClient.Extension("STARTTLS")
  145. if !isSecureConn && hasStartTLS {
  146. if err = smtpClient.StartTLS(tlsconfig); err != nil {
  147. return fmt.Errorf("start tls: %v", err)
  148. }
  149. }
  150. canAuth, options := smtpClient.Extension("AUTH")
  151. if canAuth {
  152. var auth smtp.Auth
  153. if strings.Contains(options, "CRAM-MD5") {
  154. auth = smtp.CRAMMD5Auth(sender, smtpPassword)
  155. } else if strings.Contains(options, "PLAIN") {
  156. auth = smtp.PlainAuth("", sender, smtpPassword, host)
  157. } else if strings.Contains(options, "LOGIN") {
  158. auth = LoginAuth(sender, smtpPassword)
  159. }
  160. if auth != nil {
  161. if err = smtpClient.Auth(auth); err != nil {
  162. return fmt.Errorf("auth: %s", err.Error())
  163. }
  164. }
  165. }
  166. err = smtpClient.Mail(sender)
  167. if err != nil {
  168. return fmt.Errorf("mail: %v", err)
  169. }
  170. recList := make([]string, 0, len(toAddr))
  171. for _, addr := range toAddr {
  172. if addr.Address == "" || !utils.IsValidEmail(addr.Address) {
  173. fmt.Printf("%s is not a valid email, ignore\n", addr.Address)
  174. continue
  175. }
  176. err = smtpClient.Rcpt(addr.Address)
  177. if err != nil {
  178. fmt.Printf("%s set rcpt error: %s, ignore\n", addr.String(), err.Error())
  179. continue
  180. }
  181. recList = append(recList, addr.String())
  182. }
  183. if len(recList) == 0 {
  184. return fmt.Errorf("no any valid recipient")
  185. }
  186. if fromAddr.Address == "" {
  187. fromAddr.Address = smtpUser
  188. }
  189. gomsg := gomail.NewMessage()
  190. gomsg.SetHeader("From", fromAddr.String())
  191. gomsg.SetHeader("To", recList...)
  192. gomsg.SetHeader("Reply-To", replyToAddr.String())
  193. gomsg.SetHeader("Subject", subject)
  194. gomsg.SetDateHeader("Date", t)
  195. if messageID != "" {
  196. gomsg.SetHeader("In-Reply-To", messageID)
  197. gomsg.SetHeader("References", messageID)
  198. }
  199. gomsg.SetBody("text/plain", msg)
  200. w, err := smtpClient.Data()
  201. if err != nil {
  202. return fmt.Errorf("data: %v", err)
  203. }
  204. if _, err = gomsg.WriteTo(w); err != nil {
  205. return fmt.Errorf("write to: %v", err)
  206. }
  207. err = w.Close()
  208. if err != nil {
  209. return fmt.Errorf("close: %v", err)
  210. }
  211. return nil
  212. }
  213. type loginAuth struct {
  214. username, password string
  215. }
  216. func (*loginAuth) Start(_ *smtp.ServerInfo) (string, []byte, error) {
  217. return "LOGIN", []byte{}, nil
  218. }
  219. func (a *loginAuth) Next(fromServer []byte, more bool) ([]byte, error) {
  220. if more {
  221. switch string(fromServer) {
  222. case "Username:":
  223. return []byte(a.username), nil
  224. case "Password:":
  225. return []byte(a.password), nil
  226. default:
  227. return nil, fmt.Errorf("unknwon fromServer: %s", string(fromServer))
  228. }
  229. }
  230. return nil, nil
  231. }
  232. func LoginAuth(username, password string) smtp.Auth {
  233. return &loginAuth{username, password}
  234. }
  235. type Message struct {
  236. Info string // Message information for log purpose.
  237. *gomail.Message
  238. confirmChan chan struct{}
  239. }