mailer.go 4.5 KB

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