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.

230 lines
4.8 KiB

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