message.go 6.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252
  1. // Copyright 2014 The Gogs Authors. All rights reserved.
  2. // Use of this source code is governed by a MIT-style
  3. // license that can be found in the LICENSE and LICENSE.gogs file.
  4. package email
  5. import (
  6. "crypto/tls"
  7. "fmt"
  8. "io"
  9. "net"
  10. "net/smtp"
  11. "os"
  12. "strings"
  13. "time"
  14. "github.com/jaytaylor/html2text"
  15. "gopkg.in/gomail.v2"
  16. log "unknwon.dev/clog/v2"
  17. "github.com/SongZihuan/huan-gogs/internal/conf"
  18. )
  19. type Message struct {
  20. Info string // Message information for log purpose.
  21. *gomail.Message
  22. confirmChan chan struct{}
  23. }
  24. // NewMessageFrom creates new mail message object with custom From header.
  25. func NewMessageFrom(to []string, from, subject, htmlBody string) *Message {
  26. log.Trace("NewMessageFrom (htmlBody):\n%s", htmlBody)
  27. msg := gomail.NewMessage()
  28. msg.SetHeader("From", from)
  29. msg.SetHeader("To", to...)
  30. msg.SetHeader("Subject", conf.Email.SubjectPrefix+subject)
  31. msg.SetDateHeader("Date", time.Now())
  32. contentType := "text/html"
  33. body := htmlBody
  34. switchedToPlaintext := false
  35. if conf.Email.UsePlainText || conf.Email.AddPlainTextAlt {
  36. plainBody, err := html2text.FromString(htmlBody)
  37. if err != nil {
  38. log.Error("html2text.FromString: %v", err)
  39. } else {
  40. contentType = "text/plain"
  41. body = plainBody
  42. switchedToPlaintext = true
  43. }
  44. }
  45. msg.SetBody(contentType, body)
  46. if switchedToPlaintext && conf.Email.AddPlainTextAlt && !conf.Email.UsePlainText {
  47. // The AddAlternative method name is confusing - adding html as an "alternative" will actually cause mail
  48. // clients to show it as first priority, and the text "main body" is the 2nd priority fallback.
  49. // See: https://godoc.org/gopkg.in/gomail.v2#Message.AddAlternative
  50. msg.AddAlternative("text/html", htmlBody)
  51. }
  52. return &Message{
  53. Message: msg,
  54. confirmChan: make(chan struct{}),
  55. }
  56. }
  57. // NewMessage creates new mail message object with default From header.
  58. func NewMessage(to []string, subject, body string) *Message {
  59. return NewMessageFrom(to, conf.Email.FromEmail.String(), subject, body)
  60. }
  61. type loginAuth struct {
  62. username, password string
  63. }
  64. // SMTP AUTH LOGIN Auth Handler
  65. func LoginAuth(username, password string) smtp.Auth {
  66. return &loginAuth{username, password}
  67. }
  68. func (*loginAuth) Start(_ *smtp.ServerInfo) (string, []byte, error) {
  69. return "LOGIN", []byte{}, nil
  70. }
  71. func (a *loginAuth) Next(fromServer []byte, more bool) ([]byte, error) {
  72. if more {
  73. switch string(fromServer) {
  74. case "Username:":
  75. return []byte(a.username), nil
  76. case "Password:":
  77. return []byte(a.password), nil
  78. default:
  79. return nil, fmt.Errorf("unknwon fromServer: %s", string(fromServer))
  80. }
  81. }
  82. return nil, nil
  83. }
  84. type Sender struct{}
  85. func (*Sender) Send(from string, to []string, msg io.WriterTo) error {
  86. opts := conf.Email
  87. host, port, err := net.SplitHostPort(opts.Host)
  88. if err != nil {
  89. return err
  90. }
  91. tlsconfig := &tls.Config{
  92. InsecureSkipVerify: opts.SkipVerify,
  93. ServerName: host,
  94. }
  95. if opts.UseCertificate {
  96. cert, err := tls.LoadX509KeyPair(opts.CertFile, opts.KeyFile)
  97. if err != nil {
  98. return err
  99. }
  100. tlsconfig.Certificates = []tls.Certificate{cert}
  101. }
  102. conn, err := net.Dial("tcp", net.JoinHostPort(host, port))
  103. if err != nil {
  104. return err
  105. }
  106. defer func() {
  107. _ = conn.Close()
  108. }()
  109. isSecureConn := false
  110. _conn := tls.Client(conn, tlsconfig)
  111. err = _conn.Handshake()
  112. if err == nil {
  113. conn = _conn
  114. isSecureConn = true
  115. }
  116. client, err := smtp.NewClient(conn, host)
  117. if err != nil {
  118. return fmt.Errorf("NewClient: %v", err)
  119. }
  120. if !opts.DisableHELO {
  121. hostname := opts.HELOHostname
  122. if hostname == "" {
  123. hostname, err = os.Hostname()
  124. if err != nil {
  125. return err
  126. }
  127. }
  128. if err = client.Hello(hostname); err != nil {
  129. return fmt.Errorf("Hello: %v", err)
  130. }
  131. }
  132. // If not using SMTPS, always use STARTTLS if available
  133. hasStartTLS, _ := client.Extension("STARTTLS")
  134. if !isSecureConn && hasStartTLS {
  135. if err = client.StartTLS(tlsconfig); err != nil {
  136. return fmt.Errorf("StartTLS: %v", err)
  137. }
  138. }
  139. canAuth, options := client.Extension("AUTH")
  140. if canAuth && len(opts.User) > 0 {
  141. var auth smtp.Auth
  142. if strings.Contains(options, "CRAM-MD5") {
  143. auth = smtp.CRAMMD5Auth(opts.User, opts.Password)
  144. } else if strings.Contains(options, "PLAIN") {
  145. auth = smtp.PlainAuth("", opts.User, opts.Password, host)
  146. } else if strings.Contains(options, "LOGIN") {
  147. // Patch for AUTH LOGIN
  148. auth = LoginAuth(opts.User, opts.Password)
  149. }
  150. if auth != nil {
  151. if err = client.Auth(auth); err != nil {
  152. return fmt.Errorf("Auth: %v", err)
  153. }
  154. }
  155. }
  156. if err = client.Mail(from); err != nil {
  157. return fmt.Errorf("Mail: %v", err)
  158. }
  159. for _, rec := range to {
  160. if err = client.Rcpt(rec); err != nil {
  161. return fmt.Errorf("Rcpt: %v", err)
  162. }
  163. }
  164. w, err := client.Data()
  165. if err != nil {
  166. return fmt.Errorf("Data: %v", err)
  167. } else if _, err = msg.WriteTo(w); err != nil {
  168. return fmt.Errorf("WriteTo: %v", err)
  169. } else if err = w.Close(); err != nil {
  170. return fmt.Errorf("Close: %v", err)
  171. }
  172. return client.Quit()
  173. }
  174. func processMailQueue() {
  175. sender := &Sender{}
  176. for msg := range mailQueue {
  177. log.Trace("New e-mail sending request %s: %s", msg.GetHeader("To"), msg.Info)
  178. if err := gomail.Send(sender, msg.Message); err != nil {
  179. log.Error("Failed to send emails %s: %s - %v", msg.GetHeader("To"), msg.Info, err)
  180. } else {
  181. log.Trace("E-mails sent %s: %s", msg.GetHeader("To"), msg.Info)
  182. }
  183. msg.confirmChan <- struct{}{}
  184. }
  185. }
  186. var mailQueue chan *Message
  187. // NewContext initializes settings for mailer.
  188. func NewContext() {
  189. // Need to check if mailQueue is nil because in during reinstall (user had installed
  190. // before but switched install lock off), this function will be called again
  191. // while mail queue is already processing tasks, and produces a race condition.
  192. if !conf.Email.Enabled || mailQueue != nil {
  193. return
  194. }
  195. mailQueue = make(chan *Message, 1000)
  196. go processMailQueue()
  197. }
  198. // Send puts new message object into mail queue.
  199. // It returns without confirmation (mail processed asynchronously) in normal cases,
  200. // but waits/blocks under hook mode to make sure mail has been sent.
  201. func Send(msg *Message) {
  202. if !conf.Email.Enabled {
  203. return
  204. }
  205. mailQueue <- msg
  206. if conf.HookMode {
  207. <-msg.confirmChan
  208. return
  209. }
  210. go func() {
  211. <-msg.confirmChan
  212. }()
  213. }