mailer.go 4.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213
  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 file.
  4. package mailer
  5. import (
  6. "crypto/tls"
  7. "fmt"
  8. "net"
  9. "net/mail"
  10. "net/smtp"
  11. "strings"
  12. "github.com/gogits/gogs/modules/log"
  13. "github.com/gogits/gogs/modules/setting"
  14. )
  15. type Message struct {
  16. To []string
  17. From string
  18. Subject string
  19. Body string
  20. Type string
  21. Massive bool
  22. Info string
  23. }
  24. // create mail content
  25. func (m Message) Content() string {
  26. // set mail type
  27. contentType := "text/plain; charset=UTF-8"
  28. if m.Type == "html" {
  29. contentType = "text/html; charset=UTF-8"
  30. }
  31. // create mail content
  32. content := "From: " + m.From + "\r\nSubject: " + m.Subject + "\r\nContent-Type: " + contentType + "\r\n\r\n" + m.Body
  33. return content
  34. }
  35. var mailQueue chan *Message
  36. func NewMailerContext() {
  37. mailQueue = make(chan *Message, setting.Cfg.Section("mailer").Key("SEND_BUFFER_LEN").MustInt(10))
  38. go processMailQueue()
  39. }
  40. func processMailQueue() {
  41. for {
  42. select {
  43. case msg := <-mailQueue:
  44. num, err := Send(msg)
  45. tos := strings.Join(msg.To, "; ")
  46. info := ""
  47. if err != nil {
  48. if len(msg.Info) > 0 {
  49. info = ", info: " + msg.Info
  50. }
  51. log.Error(4, fmt.Sprintf("Async sent email %d succeed, not send emails: %s%s err: %s", num, tos, info, err))
  52. } else {
  53. log.Trace(fmt.Sprintf("Async sent email %d succeed, sent emails: %s%s", num, tos, info))
  54. }
  55. }
  56. }
  57. }
  58. // sendMail allows mail with self-signed certificates.
  59. func sendMail(settings *setting.Mailer, recipients []string, msgContent []byte) error {
  60. host, port, err := net.SplitHostPort(settings.Host)
  61. if err != nil {
  62. return err
  63. }
  64. cert, err := tls.LoadX509KeyPair(settings.CertFile, settings.KeyFile)
  65. if err != nil {
  66. return err
  67. }
  68. tlsconfig := &tls.Config{
  69. InsecureSkipVerify: settings.SkipVerify,
  70. ServerName: host,
  71. Certificates: []tls.Certificate{cert},
  72. }
  73. conn, err := net.Dial("tcp", net.JoinHostPort(host, port))
  74. if err != nil {
  75. return err
  76. }
  77. defer conn.Close()
  78. isSecureConn := false
  79. // Start TLS directly if the port ends with 465 (SMTPS protocol)
  80. if strings.HasSuffix(port, "465") {
  81. conn = tls.Client(conn, tlsconfig)
  82. isSecureConn = true
  83. }
  84. client, err := smtp.NewClient(conn, host)
  85. if err != nil {
  86. return err
  87. }
  88. // If not using SMTPS, alway use STARTTLS if available
  89. hasStartTLS, _ := client.Extension("STARTTLS")
  90. if !isSecureConn && hasStartTLS {
  91. if err = client.StartTLS(tlsconfig); err != nil {
  92. return err
  93. }
  94. }
  95. canAuth, options := client.Extension("AUTH")
  96. if canAuth && len(settings.User) > 0 {
  97. var auth smtp.Auth
  98. if strings.Contains(options, "CRAM-MD5") {
  99. auth = smtp.CRAMMD5Auth(settings.User, settings.Passwd)
  100. } else if strings.Contains(options, "PLAIN") {
  101. auth = smtp.PlainAuth("", settings.User, settings.Passwd, host)
  102. }
  103. if auth != nil {
  104. if err = client.Auth(auth); err != nil {
  105. return err
  106. }
  107. }
  108. }
  109. if fromAddress, err := mail.ParseAddress(settings.From); err != nil {
  110. return err
  111. } else {
  112. if err = client.Mail(fromAddress.Address); err != nil {
  113. return err
  114. }
  115. }
  116. for _, rec := range recipients {
  117. if err = client.Rcpt(rec); err != nil {
  118. return err
  119. }
  120. }
  121. w, err := client.Data()
  122. if err != nil {
  123. return err
  124. }
  125. if _, err = w.Write([]byte(msgContent)); err != nil {
  126. return err
  127. }
  128. if err = w.Close(); err != nil {
  129. return err
  130. }
  131. return client.Quit()
  132. }
  133. // Direct Send mail message
  134. func Send(msg *Message) (int, error) {
  135. log.Trace("Sending mails to: %s", strings.Join(msg.To, "; "))
  136. // get message body
  137. content := msg.Content()
  138. if len(msg.To) == 0 {
  139. return 0, fmt.Errorf("empty receive emails")
  140. } else if len(msg.Body) == 0 {
  141. return 0, fmt.Errorf("empty email body")
  142. }
  143. if msg.Massive {
  144. // send mail to multiple emails one by one
  145. num := 0
  146. for _, to := range msg.To {
  147. body := []byte("To: " + to + "\r\n" + content)
  148. err := sendMail(setting.MailService, []string{to}, body)
  149. if err != nil {
  150. return num, err
  151. }
  152. num++
  153. }
  154. return num, nil
  155. } else {
  156. body := []byte("To: " + strings.Join(msg.To, ";") + "\r\n" + content)
  157. // send to multiple emails in one message
  158. err := sendMail(setting.MailService, msg.To, body)
  159. if err != nil {
  160. return 0, err
  161. } else {
  162. return 1, nil
  163. }
  164. }
  165. }
  166. // Async Send mail message
  167. func SendAsync(msg *Message) {
  168. go func() {
  169. mailQueue <- msg
  170. }()
  171. }
  172. // Create html mail message
  173. func NewHtmlMessage(To []string, From, Subject, Body string) Message {
  174. return Message{
  175. To: To,
  176. From: From,
  177. Subject: Subject,
  178. Body: Body,
  179. Type: "html",
  180. }
  181. }