mailer.go 5.6 KB

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