mailer.go 4.5 KB

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