mailer.go 4.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215
  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. tlsconfig := &tls.Config{
  65. InsecureSkipVerify: settings.SkipVerify,
  66. ServerName: host,
  67. }
  68. if settings.UseCertificate {
  69. cert, err := tls.LoadX509KeyPair(settings.CertFile, settings.KeyFile)
  70. if err != nil {
  71. return err
  72. }
  73. tlsconfig.Certificates = []tls.Certificate{cert}
  74. }
  75. conn, err := net.Dial("tcp", net.JoinHostPort(host, port))
  76. if err != nil {
  77. return err
  78. }
  79. defer conn.Close()
  80. isSecureConn := false
  81. // Start TLS directly if the port ends with 465 (SMTPS protocol)
  82. if strings.HasSuffix(port, "465") {
  83. conn = tls.Client(conn, tlsconfig)
  84. isSecureConn = true
  85. }
  86. client, err := smtp.NewClient(conn, host)
  87. if err != nil {
  88. return err
  89. }
  90. // If not using SMTPS, alway use STARTTLS if available
  91. hasStartTLS, _ := client.Extension("STARTTLS")
  92. if !isSecureConn && hasStartTLS {
  93. if err = client.StartTLS(tlsconfig); err != nil {
  94. return err
  95. }
  96. }
  97. canAuth, options := client.Extension("AUTH")
  98. if canAuth && len(settings.User) > 0 {
  99. var auth smtp.Auth
  100. if strings.Contains(options, "CRAM-MD5") {
  101. auth = smtp.CRAMMD5Auth(settings.User, settings.Passwd)
  102. } else if strings.Contains(options, "PLAIN") {
  103. auth = smtp.PlainAuth("", settings.User, settings.Passwd, host)
  104. }
  105. if auth != nil {
  106. if err = client.Auth(auth); err != nil {
  107. return err
  108. }
  109. }
  110. }
  111. if fromAddress, err := mail.ParseAddress(settings.From); err != nil {
  112. return err
  113. } else {
  114. if err = client.Mail(fromAddress.Address); err != nil {
  115. return err
  116. }
  117. }
  118. for _, rec := range recipients {
  119. if err = client.Rcpt(rec); err != nil {
  120. return err
  121. }
  122. }
  123. w, err := client.Data()
  124. if err != nil {
  125. return err
  126. }
  127. if _, err = w.Write([]byte(msgContent)); err != nil {
  128. return err
  129. }
  130. if err = w.Close(); err != nil {
  131. return err
  132. }
  133. return client.Quit()
  134. }
  135. // Direct Send mail message
  136. func Send(msg *Message) (int, error) {
  137. log.Trace("Sending mails to: %s", strings.Join(msg.To, "; "))
  138. // get message body
  139. content := msg.Content()
  140. if len(msg.To) == 0 {
  141. return 0, fmt.Errorf("empty receive emails")
  142. } else if len(msg.Body) == 0 {
  143. return 0, fmt.Errorf("empty email body")
  144. }
  145. if msg.Massive {
  146. // send mail to multiple emails one by one
  147. num := 0
  148. for _, to := range msg.To {
  149. body := []byte("To: " + to + "\r\n" + content)
  150. err := sendMail(setting.MailService, []string{to}, body)
  151. if err != nil {
  152. return num, err
  153. }
  154. num++
  155. }
  156. return num, nil
  157. } else {
  158. body := []byte("To: " + strings.Join(msg.To, ";") + "\r\n" + content)
  159. // send to multiple emails in one message
  160. err := sendMail(setting.MailService, msg.To, body)
  161. if err != nil {
  162. return 0, err
  163. } else {
  164. return 1, nil
  165. }
  166. }
  167. }
  168. // Async Send mail message
  169. func SendAsync(msg *Message) {
  170. go func() {
  171. mailQueue <- msg
  172. }()
  173. }
  174. // Create html mail message
  175. func NewHtmlMessage(To []string, From, Subject, Body string) Message {
  176. return Message{
  177. To: To,
  178. From: From,
  179. Subject: Subject,
  180. Body: Body,
  181. Type: "html",
  182. }
  183. }