email.go 6.3 KB

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