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.

mail.go 2.1KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889
  1. // Copyright 2020 The Gitea 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 private
  5. import (
  6. "encoding/json"
  7. "fmt"
  8. "net/http"
  9. "strconv"
  10. "code.gitea.io/gitea/models"
  11. "code.gitea.io/gitea/modules/log"
  12. "code.gitea.io/gitea/modules/private"
  13. "code.gitea.io/gitea/modules/setting"
  14. "code.gitea.io/gitea/services/mailer"
  15. "gitea.com/macaron/macaron"
  16. )
  17. // SendEmail pushes messages to mail queue
  18. //
  19. // It doesn't wait before each message will be processed
  20. func SendEmail(ctx *macaron.Context) {
  21. if setting.MailService == nil {
  22. ctx.JSON(http.StatusInternalServerError, map[string]interface{}{
  23. "err": "Mail service is not enabled.",
  24. })
  25. return
  26. }
  27. var mail private.Email
  28. rd := ctx.Req.Body().ReadCloser()
  29. defer rd.Close()
  30. if err := json.NewDecoder(rd).Decode(&mail); err != nil {
  31. log.Error("%v", err)
  32. ctx.JSON(http.StatusInternalServerError, map[string]interface{}{
  33. "err": err,
  34. })
  35. return
  36. }
  37. var emails []string
  38. if len(mail.To) > 0 {
  39. for _, uname := range mail.To {
  40. user, err := models.GetUserByName(uname)
  41. if err != nil {
  42. err := fmt.Sprintf("Failed to get user information: %v", err)
  43. log.Error(err)
  44. ctx.JSON(http.StatusInternalServerError, map[string]interface{}{
  45. "err": err,
  46. })
  47. return
  48. }
  49. if user != nil && len(user.Email) > 0 {
  50. emails = append(emails, user.Email)
  51. }
  52. }
  53. } else {
  54. err := models.IterateUser(func(user *models.User) error {
  55. if len(user.Email) > 0 {
  56. emails = append(emails, user.Email)
  57. }
  58. return nil
  59. })
  60. if err != nil {
  61. err := fmt.Sprintf("Failed to find users: %v", err)
  62. log.Error(err)
  63. ctx.JSON(http.StatusInternalServerError, map[string]interface{}{
  64. "err": err,
  65. })
  66. return
  67. }
  68. }
  69. sendEmail(ctx, mail.Subject, mail.Message, emails)
  70. }
  71. func sendEmail(ctx *macaron.Context, subject, message string, to []string) {
  72. for _, email := range to {
  73. msg := mailer.NewMessage([]string{email}, subject, message)
  74. mailer.SendAsync(msg)
  75. }
  76. wasSent := strconv.Itoa(len(to))
  77. ctx.PlainText(http.StatusOK, []byte(wasSent))
  78. }