1
0

email.go 6.1 KB

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