email.go 6.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227
  1. // Copyright 2016 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 email
  5. import (
  6. "fmt"
  7. "html/template"
  8. "path/filepath"
  9. "sync"
  10. "time"
  11. "gopkg.in/gomail.v2"
  12. "gopkg.in/macaron.v1"
  13. log "unknwon.dev/clog/v2"
  14. "gogs.io/gogs/internal/conf"
  15. "gogs.io/gogs/internal/markup"
  16. "gogs.io/gogs/templates"
  17. )
  18. const (
  19. MAIL_AUTH_ACTIVATE = "auth/activate"
  20. MAIL_AUTH_ACTIVATE_EMAIL = "auth/activate_email"
  21. MAIL_AUTH_RESET_PASSWORD = "auth/reset_passwd"
  22. MAIL_AUTH_REGISTER_NOTIFY = "auth/register_notify"
  23. MAIL_ISSUE_COMMENT = "issue/comment"
  24. MAIL_ISSUE_MENTION = "issue/mention"
  25. MAIL_NOTIFY_COLLABORATOR = "notify/collaborator"
  26. )
  27. var (
  28. tplRender *macaron.TplRender
  29. tplRenderOnce sync.Once
  30. )
  31. // render renders a mail template with given data.
  32. func render(tpl string, data map[string]any) (string, error) {
  33. tplRenderOnce.Do(func() {
  34. opt := &macaron.RenderOptions{
  35. Directory: filepath.Join(conf.WorkDir(), "templates", "mail"),
  36. AppendDirectories: []string{filepath.Join(conf.CustomDir(), "templates", "mail")},
  37. Extensions: []string{".tmpl", ".html"},
  38. Funcs: []template.FuncMap{map[string]any{
  39. "AppName": func() string {
  40. return conf.App.BrandName
  41. },
  42. "AppURL": func() string {
  43. return conf.Server.ExternalURL
  44. },
  45. "Year": func() int {
  46. return time.Now().Year()
  47. },
  48. "Str2HTML": func(raw string) template.HTML {
  49. return template.HTML(markup.Sanitize(raw))
  50. },
  51. }},
  52. }
  53. if !conf.Server.LoadAssetsFromDisk {
  54. opt.TemplateFileSystem = templates.NewTemplateFileSystem("mail", opt.AppendDirectories[0])
  55. }
  56. ts := macaron.NewTemplateSet()
  57. ts.Set(macaron.DEFAULT_TPL_SET_NAME, opt)
  58. tplRender = &macaron.TplRender{
  59. TemplateSet: ts,
  60. Opt: opt,
  61. }
  62. })
  63. return tplRender.HTMLString(tpl, data)
  64. }
  65. func SendTestMail(email string) error {
  66. return gomail.Send(&Sender{}, NewMessage([]string{email}, "Gogs Test Email", "Hello 👋, greeting from Gogs!").Message)
  67. }
  68. /*
  69. Setup interfaces of used methods in mail to avoid cycle import.
  70. */
  71. type User interface {
  72. ID() int64
  73. DisplayName() string
  74. Email() string
  75. GenerateEmailActivateCode(string) string
  76. }
  77. type Repository interface {
  78. FullName() string
  79. HTMLURL() string
  80. ComposeMetas() map[string]string
  81. }
  82. type Issue interface {
  83. MailSubject() string
  84. Content() string
  85. HTMLURL() string
  86. }
  87. func SendUserMail(_ *macaron.Context, u User, tpl, code, subject, info string) {
  88. data := map[string]any{
  89. "Username": u.DisplayName(),
  90. "ActiveCodeLives": conf.Auth.ActivateCodeLives / 60,
  91. "ResetPwdCodeLives": conf.Auth.ResetPasswordCodeLives / 60,
  92. "Code": code,
  93. }
  94. body, err := render(tpl, data)
  95. if err != nil {
  96. log.Error("render: %v", err)
  97. return
  98. }
  99. msg := NewMessage([]string{u.Email()}, subject, body)
  100. msg.Info = fmt.Sprintf("UID: %d, %s", u.ID(), info)
  101. Send(msg)
  102. }
  103. func SendActivateAccountMail(c *macaron.Context, u User) {
  104. SendUserMail(c, u, MAIL_AUTH_ACTIVATE, u.GenerateEmailActivateCode(u.Email()), c.Tr("mail.activate_account"), "activate account")
  105. }
  106. func SendResetPasswordMail(c *macaron.Context, u User) {
  107. SendUserMail(c, u, MAIL_AUTH_RESET_PASSWORD, u.GenerateEmailActivateCode(u.Email()), c.Tr("mail.reset_password"), "reset password")
  108. }
  109. // SendActivateAccountMail sends confirmation email.
  110. func SendActivateEmailMail(c *macaron.Context, u User, email string) {
  111. data := map[string]any{
  112. "Username": u.DisplayName(),
  113. "ActiveCodeLives": conf.Auth.ActivateCodeLives / 60,
  114. "Code": u.GenerateEmailActivateCode(email),
  115. "Email": email,
  116. }
  117. body, err := render(MAIL_AUTH_ACTIVATE_EMAIL, data)
  118. if err != nil {
  119. log.Error("HTMLString: %v", err)
  120. return
  121. }
  122. msg := NewMessage([]string{email}, c.Tr("mail.activate_email"), body)
  123. msg.Info = fmt.Sprintf("UID: %d, activate email", u.ID())
  124. Send(msg)
  125. }
  126. // SendRegisterNotifyMail triggers a notify e-mail by admin created a account.
  127. func SendRegisterNotifyMail(c *macaron.Context, u User) {
  128. data := map[string]any{
  129. "Username": u.DisplayName(),
  130. }
  131. body, err := render(MAIL_AUTH_REGISTER_NOTIFY, data)
  132. if err != nil {
  133. log.Error("HTMLString: %v", err)
  134. return
  135. }
  136. msg := NewMessage([]string{u.Email()}, c.Tr("mail.register_notify"), body)
  137. msg.Info = fmt.Sprintf("UID: %d, registration notify", u.ID())
  138. Send(msg)
  139. }
  140. // SendCollaboratorMail sends mail notification to new collaborator.
  141. func SendCollaboratorMail(u, doer User, repo Repository) {
  142. subject := fmt.Sprintf("%s added you to %s", doer.DisplayName(), repo.FullName())
  143. data := map[string]any{
  144. "Subject": subject,
  145. "RepoName": repo.FullName(),
  146. "Link": repo.HTMLURL(),
  147. }
  148. body, err := render(MAIL_NOTIFY_COLLABORATOR, data)
  149. if err != nil {
  150. log.Error("HTMLString: %v", err)
  151. return
  152. }
  153. msg := NewMessage([]string{u.Email()}, subject, body)
  154. msg.Info = fmt.Sprintf("UID: %d, add collaborator", u.ID())
  155. Send(msg)
  156. }
  157. func composeTplData(subject, body, link string) map[string]any {
  158. data := make(map[string]any, 10)
  159. data["Subject"] = subject
  160. data["Body"] = body
  161. data["Link"] = link
  162. return data
  163. }
  164. func composeIssueMessage(issue Issue, repo Repository, doer User, tplName string, tos []string, info string) *Message {
  165. subject := issue.MailSubject()
  166. body := string(markup.Markdown([]byte(issue.Content()), repo.HTMLURL(), repo.ComposeMetas()))
  167. data := composeTplData(subject, body, issue.HTMLURL())
  168. data["Doer"] = doer
  169. content, err := render(tplName, data)
  170. if err != nil {
  171. log.Error("HTMLString (%s): %v", tplName, err)
  172. }
  173. from := gomail.NewMessage().FormatAddress(conf.Email.FromEmail, doer.DisplayName())
  174. msg := NewMessageFrom(tos, from, subject, content)
  175. msg.Info = fmt.Sprintf("Subject: %s, %s", subject, info)
  176. return msg
  177. }
  178. // SendIssueCommentMail composes and sends issue comment emails to target receivers.
  179. func SendIssueCommentMail(issue Issue, repo Repository, doer User, tos []string) {
  180. if len(tos) == 0 {
  181. return
  182. }
  183. Send(composeIssueMessage(issue, repo, doer, MAIL_ISSUE_COMMENT, tos, "issue comment"))
  184. }
  185. // SendIssueMentionMail composes and sends issue mention emails to target receivers.
  186. func SendIssueMentionMail(issue Issue, repo Repository, doer User, tos []string) {
  187. if len(tos) == 0 {
  188. return
  189. }
  190. Send(composeIssueMessage(issue, repo, doer, MAIL_ISSUE_MENTION, tos, "issue mention"))
  191. }