mail.go 6.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228
  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 mailer
  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/assets/templates"
  15. "gogs.io/gogs/internal/conf"
  16. "gogs.io/gogs/internal/markup"
  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]interface{}) (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]interface{}{
  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. GenerateActivateCode() string
  76. GenerateEmailActivateCode(string) string
  77. }
  78. type Repository interface {
  79. FullName() string
  80. HTMLURL() string
  81. ComposeMetas() map[string]string
  82. }
  83. type Issue interface {
  84. MailSubject() string
  85. Content() string
  86. HTMLURL() string
  87. }
  88. func SendUserMail(c *macaron.Context, u User, tpl, code, subject, info string) {
  89. data := map[string]interface{}{
  90. "Username": u.DisplayName(),
  91. "ActiveCodeLives": conf.Service.ActiveCodeLives / 60,
  92. "ResetPwdCodeLives": conf.Service.ResetPwdCodeLives / 60,
  93. "Code": code,
  94. }
  95. body, err := render(tpl, data)
  96. if err != nil {
  97. log.Error("render: %v", err)
  98. return
  99. }
  100. msg := NewMessage([]string{u.Email()}, subject, body)
  101. msg.Info = fmt.Sprintf("UID: %d, %s", u.ID(), info)
  102. Send(msg)
  103. }
  104. func SendActivateAccountMail(c *macaron.Context, u User) {
  105. SendUserMail(c, u, MAIL_AUTH_ACTIVATE, u.GenerateActivateCode(), c.Tr("mail.activate_account"), "activate account")
  106. }
  107. func SendResetPasswordMail(c *macaron.Context, u User) {
  108. SendUserMail(c, u, MAIL_AUTH_RESET_PASSWORD, u.GenerateActivateCode(), c.Tr("mail.reset_password"), "reset password")
  109. }
  110. // SendActivateAccountMail sends confirmation email.
  111. func SendActivateEmailMail(c *macaron.Context, u User, email string) {
  112. data := map[string]interface{}{
  113. "Username": u.DisplayName(),
  114. "ActiveCodeLives": conf.Service.ActiveCodeLives / 60,
  115. "Code": u.GenerateEmailActivateCode(email),
  116. "Email": email,
  117. }
  118. body, err := render(MAIL_AUTH_ACTIVATE_EMAIL, data)
  119. if err != nil {
  120. log.Error("HTMLString: %v", err)
  121. return
  122. }
  123. msg := NewMessage([]string{email}, c.Tr("mail.activate_email"), body)
  124. msg.Info = fmt.Sprintf("UID: %d, activate email", u.ID())
  125. Send(msg)
  126. }
  127. // SendRegisterNotifyMail triggers a notify e-mail by admin created a account.
  128. func SendRegisterNotifyMail(c *macaron.Context, u User) {
  129. data := map[string]interface{}{
  130. "Username": u.DisplayName(),
  131. }
  132. body, err := render(MAIL_AUTH_REGISTER_NOTIFY, data)
  133. if err != nil {
  134. log.Error("HTMLString: %v", err)
  135. return
  136. }
  137. msg := NewMessage([]string{u.Email()}, c.Tr("mail.register_notify"), body)
  138. msg.Info = fmt.Sprintf("UID: %d, registration notify", u.ID())
  139. Send(msg)
  140. }
  141. // SendCollaboratorMail sends mail notification to new collaborator.
  142. func SendCollaboratorMail(u, doer User, repo Repository) {
  143. subject := fmt.Sprintf("%s added you to %s", doer.DisplayName(), repo.FullName())
  144. data := map[string]interface{}{
  145. "Subject": subject,
  146. "RepoName": repo.FullName(),
  147. "Link": repo.HTMLURL(),
  148. }
  149. body, err := render(MAIL_NOTIFY_COLLABORATOR, data)
  150. if err != nil {
  151. log.Error("HTMLString: %v", err)
  152. return
  153. }
  154. msg := NewMessage([]string{u.Email()}, subject, body)
  155. msg.Info = fmt.Sprintf("UID: %d, add collaborator", u.ID())
  156. Send(msg)
  157. }
  158. func composeTplData(subject, body, link string) map[string]interface{} {
  159. data := make(map[string]interface{}, 10)
  160. data["Subject"] = subject
  161. data["Body"] = body
  162. data["Link"] = link
  163. return data
  164. }
  165. func composeIssueMessage(issue Issue, repo Repository, doer User, tplName string, tos []string, info string) *Message {
  166. subject := issue.MailSubject()
  167. body := string(markup.Markdown([]byte(issue.Content()), repo.HTMLURL(), repo.ComposeMetas()))
  168. data := composeTplData(subject, body, issue.HTMLURL())
  169. data["Doer"] = doer
  170. content, err := render(tplName, data)
  171. if err != nil {
  172. log.Error("HTMLString (%s): %v", tplName, err)
  173. }
  174. from := gomail.NewMessage().FormatAddress(conf.MailService.FromEmail, doer.DisplayName())
  175. msg := NewMessageFrom(tos, from, subject, content)
  176. msg.Info = fmt.Sprintf("Subject: %s, %s", subject, info)
  177. return msg
  178. }
  179. // SendIssueCommentMail composes and sends issue comment emails to target receivers.
  180. func SendIssueCommentMail(issue Issue, repo Repository, doer User, tos []string) {
  181. if len(tos) == 0 {
  182. return
  183. }
  184. Send(composeIssueMessage(issue, repo, doer, MAIL_ISSUE_COMMENT, tos, "issue comment"))
  185. }
  186. // SendIssueMentionMail composes and sends issue mention emails to target receivers.
  187. func SendIssueMentionMail(issue Issue, repo Repository, doer User, tos []string) {
  188. if len(tos) == 0 {
  189. return
  190. }
  191. Send(composeIssueMessage(issue, repo, doer, MAIL_ISSUE_MENTION, tos, "issue mention"))
  192. }