You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

312 lines
7.5 KiB

  1. // Copyright 2014 The Gogs Authors. All rights reserved.
  2. // Copyright 2017 The Gitea Authors. All rights reserved.
  3. // Use of this source code is governed by a MIT-style
  4. // license that can be found in the LICENSE file.
  5. package mailer
  6. import (
  7. "bytes"
  8. "crypto/tls"
  9. "fmt"
  10. "io"
  11. "net"
  12. "net/smtp"
  13. "os"
  14. "os/exec"
  15. "strings"
  16. "time"
  17. "code.gitea.io/gitea/modules/base"
  18. "code.gitea.io/gitea/modules/log"
  19. "code.gitea.io/gitea/modules/setting"
  20. "github.com/jaytaylor/html2text"
  21. "gopkg.in/gomail.v2"
  22. )
  23. // Message mail body and log info
  24. type Message struct {
  25. Info string // Message information for log purpose.
  26. *gomail.Message
  27. }
  28. // NewMessageFrom creates new mail message object with custom From header.
  29. func NewMessageFrom(to []string, fromDisplayName, fromAddress, subject, body string) *Message {
  30. log.Trace("NewMessageFrom (body):\n%s", body)
  31. msg := gomail.NewMessage()
  32. msg.SetAddressHeader("From", fromAddress, fromDisplayName)
  33. msg.SetHeader("To", to...)
  34. if len(setting.MailService.SubjectPrefix) > 0 {
  35. msg.SetHeader("Subject", setting.MailService.SubjectPrefix+" "+subject)
  36. } else {
  37. msg.SetHeader("Subject", subject)
  38. }
  39. msg.SetDateHeader("Date", time.Now())
  40. msg.SetHeader("X-Auto-Response-Suppress", "All")
  41. plainBody, err := html2text.FromString(body)
  42. if err != nil || setting.MailService.SendAsPlainText {
  43. if strings.Contains(base.TruncateString(body, 100), "<html>") {
  44. log.Warn("Mail contains HTML but configured to send as plain text.")
  45. }
  46. msg.SetBody("text/plain", plainBody)
  47. } else {
  48. msg.SetBody("text/plain", plainBody)
  49. msg.AddAlternative("text/html", body)
  50. }
  51. return &Message{
  52. Message: msg,
  53. }
  54. }
  55. // NewMessage creates new mail message object with default From header.
  56. func NewMessage(to []string, subject, body string) *Message {
  57. return NewMessageFrom(to, setting.MailService.FromName, setting.MailService.FromEmail, subject, body)
  58. }
  59. type loginAuth struct {
  60. username, password string
  61. }
  62. // LoginAuth SMTP AUTH LOGIN Auth Handler
  63. func LoginAuth(username, password string) smtp.Auth {
  64. return &loginAuth{username, password}
  65. }
  66. // Start start SMTP login auth
  67. func (a *loginAuth) Start(server *smtp.ServerInfo) (string, []byte, error) {
  68. return "LOGIN", []byte{}, nil
  69. }
  70. // Next next step of SMTP login auth
  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("unknown fromServer: %s", string(fromServer))
  80. }
  81. }
  82. return nil, nil
  83. }
  84. // Sender SMTP mail sender
  85. type smtpSender struct {
  86. }
  87. // Send send email
  88. func (s *smtpSender) Send(from string, to []string, msg io.WriterTo) error {
  89. opts := setting.MailService
  90. host, port, err := net.SplitHostPort(opts.Host)
  91. if err != nil {
  92. return err
  93. }
  94. tlsconfig := &tls.Config{
  95. InsecureSkipVerify: opts.SkipVerify,
  96. ServerName: host,
  97. }
  98. if opts.UseCertificate {
  99. cert, err := tls.LoadX509KeyPair(opts.CertFile, opts.KeyFile)
  100. if err != nil {
  101. return err
  102. }
  103. tlsconfig.Certificates = []tls.Certificate{cert}
  104. }
  105. conn, err := net.Dial("tcp", net.JoinHostPort(host, port))
  106. if err != nil {
  107. return err
  108. }
  109. defer conn.Close()
  110. isSecureConn := opts.IsTLSEnabled || (strings.HasSuffix(port, "465"))
  111. // Start TLS directly if the port ends with 465 (SMTPS protocol)
  112. if isSecureConn {
  113. conn = tls.Client(conn, tlsconfig)
  114. }
  115. client, err := smtp.NewClient(conn, host)
  116. if err != nil {
  117. return fmt.Errorf("NewClient: %v", err)
  118. }
  119. if !opts.DisableHelo {
  120. hostname := opts.HeloHostname
  121. if len(hostname) == 0 {
  122. hostname, err = os.Hostname()
  123. if err != nil {
  124. return err
  125. }
  126. }
  127. if err = client.Hello(hostname); err != nil {
  128. return fmt.Errorf("Hello: %v", err)
  129. }
  130. }
  131. // If not using SMTPS, always use STARTTLS if available
  132. hasStartTLS, _ := client.Extension("STARTTLS")
  133. if !isSecureConn && hasStartTLS {
  134. if err = client.StartTLS(tlsconfig); err != nil {
  135. return fmt.Errorf("StartTLS: %v", err)
  136. }
  137. }
  138. canAuth, options := client.Extension("AUTH")
  139. if canAuth && len(opts.User) > 0 {
  140. var auth smtp.Auth
  141. if strings.Contains(options, "CRAM-MD5") {
  142. auth = smtp.CRAMMD5Auth(opts.User, opts.Passwd)
  143. } else if strings.Contains(options, "PLAIN") {
  144. auth = smtp.PlainAuth("", opts.User, opts.Passwd, host)
  145. } else if strings.Contains(options, "LOGIN") {
  146. // Patch for AUTH LOGIN
  147. auth = LoginAuth(opts.User, opts.Passwd)
  148. }
  149. if auth != nil {
  150. if err = client.Auth(auth); err != nil {
  151. return fmt.Errorf("Auth: %v", err)
  152. }
  153. }
  154. }
  155. if err = client.Mail(from); err != nil {
  156. return fmt.Errorf("Mail: %v", err)
  157. }
  158. for _, rec := range to {
  159. if err = client.Rcpt(rec); err != nil {
  160. return fmt.Errorf("Rcpt: %v", err)
  161. }
  162. }
  163. w, err := client.Data()
  164. if err != nil {
  165. return fmt.Errorf("Data: %v", err)
  166. } else if _, err = msg.WriteTo(w); err != nil {
  167. return fmt.Errorf("WriteTo: %v", err)
  168. } else if err = w.Close(); err != nil {
  169. return fmt.Errorf("Close: %v", err)
  170. }
  171. return client.Quit()
  172. }
  173. // Sender sendmail mail sender
  174. type sendmailSender struct {
  175. }
  176. // Send send email
  177. func (s *sendmailSender) Send(from string, to []string, msg io.WriterTo) error {
  178. var err error
  179. var closeError error
  180. var waitError error
  181. args := []string{"-F", from, "-i"}
  182. args = append(args, setting.MailService.SendmailArgs...)
  183. args = append(args, to...)
  184. log.Trace("Sending with: %s %v", setting.MailService.SendmailPath, args)
  185. cmd := exec.Command(setting.MailService.SendmailPath, args...)
  186. pipe, err := cmd.StdinPipe()
  187. if err != nil {
  188. return err
  189. }
  190. if err = cmd.Start(); err != nil {
  191. return err
  192. }
  193. _, err = msg.WriteTo(pipe)
  194. // we MUST close the pipe or sendmail will hang waiting for more of the message
  195. // Also we should wait on our sendmail command even if something fails
  196. closeError = pipe.Close()
  197. waitError = cmd.Wait()
  198. if err != nil {
  199. return err
  200. } else if closeError != nil {
  201. return closeError
  202. } else {
  203. return waitError
  204. }
  205. }
  206. // Sender sendmail mail sender
  207. type dummySender struct {
  208. }
  209. // Send send email
  210. func (s *dummySender) Send(from string, to []string, msg io.WriterTo) error {
  211. buf := bytes.Buffer{}
  212. if _, err := msg.WriteTo(&buf); err != nil {
  213. return err
  214. }
  215. log.Info("Mail From: %s To: %v Body: %s", from, to, buf.String())
  216. return nil
  217. }
  218. func processMailQueue() {
  219. for msg := range mailQueue {
  220. log.Trace("New e-mail sending request %s: %s", msg.GetHeader("To"), msg.Info)
  221. if err := gomail.Send(Sender, msg.Message); err != nil {
  222. log.Error("Failed to send emails %s: %s - %v", msg.GetHeader("To"), msg.Info, err)
  223. } else {
  224. log.Trace("E-mails sent %s: %s", msg.GetHeader("To"), msg.Info)
  225. }
  226. }
  227. }
  228. var mailQueue chan *Message
  229. // Sender sender for sending mail synchronously
  230. var Sender gomail.Sender
  231. // NewContext start mail queue service
  232. func NewContext() {
  233. // Need to check if mailQueue is nil because in during reinstall (user had installed
  234. // before but swithed install lock off), this function will be called again
  235. // while mail queue is already processing tasks, and produces a race condition.
  236. if setting.MailService == nil || mailQueue != nil {
  237. return
  238. }
  239. switch setting.MailService.MailerType {
  240. case "smtp":
  241. Sender = &smtpSender{}
  242. case "sendmail":
  243. Sender = &sendmailSender{}
  244. case "dummy":
  245. Sender = &dummySender{}
  246. }
  247. mailQueue = make(chan *Message, setting.MailService.QueueLength)
  248. go processMailQueue()
  249. }
  250. // SendAsync send mail asynchronously
  251. func SendAsync(msg *Message) {
  252. go func() {
  253. mailQueue <- msg
  254. }()
  255. }
  256. // SendAsyncs send mails asynchronously
  257. func SendAsyncs(msgs []*Message) {
  258. go func() {
  259. for _, msg := range msgs {
  260. mailQueue <- msg
  261. }
  262. }()
  263. }