1
0

message.go 6.0 KB

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