mail.go 6.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245
  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"
  9. "sync"
  10. "time"
  11. "gopkg.in/gomail.v2"
  12. "gopkg.in/macaron.v1"
  13. log "unknwon.dev/clog/v2"
  14. "github.com/G-Node/gogs/internal/assets/templates"
  15. "github.com/G-Node/gogs/internal/markup"
  16. "github.com/G-Node/gogs/internal/setting"
  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_AUTH_INVITE_NOTIFY = "auth/invite_email"
  24. MAIL_ISSUE_COMMENT = "issue/comment"
  25. MAIL_ISSUE_MENTION = "issue/mention"
  26. MAIL_NOTIFY_COLLABORATOR = "notify/collaborator"
  27. )
  28. var (
  29. tplRender *macaron.TplRender
  30. tplRenderOnce sync.Once
  31. )
  32. // render renders a mail template with given data.
  33. func render(tpl string, data map[string]interface{}) (string, error) {
  34. tplRenderOnce.Do(func() {
  35. opt := &macaron.RenderOptions{
  36. Directory: path.Join(setting.StaticRootPath, "templates/mail"),
  37. AppendDirectories: []string{path.Join(setting.CustomPath, "templates/mail")},
  38. Extensions: []string{".tmpl", ".html"},
  39. Funcs: []template.FuncMap{map[string]interface{}{
  40. "AppName": func() string {
  41. return setting.AppName
  42. },
  43. "AppURL": func() string {
  44. return setting.AppURL
  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 !setting.LoadAssetsFromDisk {
  55. opt.TemplateFileSystem = templates.NewTemplateFileSystem("mail", opt.AppendDirectories[0])
  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(email, "Gogs Test Email", "Hello 👋, greeting from 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. GenerateActivateCode() 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(c *macaron.Context, u User, tpl, code, subject, info string) {
  90. data := map[string]interface{}{
  91. "Username": u.DisplayName(),
  92. "ActiveCodeLives": setting.Service.ActiveCodeLives / 60,
  93. "ResetPwdCodeLives": setting.Service.ResetPwdCodeLives / 60,
  94. "Code": code,
  95. "Account": c.Data["Account"],
  96. "Inviter": c.Data["Inviter"],
  97. "Pw": c.Data["Pw"],
  98. }
  99. body, err := render(tpl, data)
  100. if err != nil {
  101. log.Error("render: %v", err)
  102. return
  103. }
  104. msg := NewMessage(u.Email(), subject, body)
  105. msg.Info = fmt.Sprintf("UID: %d, %s", u.ID(), info)
  106. Send(msg)
  107. }
  108. func SendActivateAccountMail(c *macaron.Context, u User) {
  109. SendUserMail(c, u, MAIL_AUTH_ACTIVATE, u.GenerateActivateCode(), c.Tr("mail.activate_account"), "activate account")
  110. }
  111. func SendInviteMail(c *macaron.Context, u User) {
  112. SendUserMail(c, u, MAIL_AUTH_INVITE_NOTIFY, u.GenerateActivateCode(), c.Tr("mail.invite_account"), "invite account")
  113. }
  114. func SendResetPasswordMail(c *macaron.Context, u User) {
  115. SendUserMail(c, u, MAIL_AUTH_RESET_PASSWORD, u.GenerateActivateCode(), c.Tr("mail.reset_password"), "reset password")
  116. }
  117. // SendActivateAccountMail sends confirmation email.
  118. func SendActivateEmailMail(c *macaron.Context, u User, email string) {
  119. data := map[string]interface{}{
  120. "Username": u.DisplayName(),
  121. "ActiveCodeLives": setting.Service.ActiveCodeLives / 60,
  122. "Code": u.GenerateEmailActivateCode(email),
  123. "Email": email,
  124. }
  125. body, err := render(MAIL_AUTH_ACTIVATE_EMAIL, data)
  126. if err != nil {
  127. log.Error("HTMLString: %v", err)
  128. return
  129. }
  130. msg := NewMessage(email, c.Tr("mail.activate_email"), body)
  131. msg.Info = fmt.Sprintf("UID: %d, activate email", u.ID())
  132. Send(msg)
  133. }
  134. // SendRegisterNotifyMail triggers a notify e-mail by admin created a account.
  135. func SendRegisterNotifyMail(c *macaron.Context, u User) {
  136. data := map[string]interface{}{
  137. "Username": u.DisplayName(),
  138. }
  139. body, err := render(MAIL_AUTH_REGISTER_NOTIFY, data)
  140. if err != nil {
  141. log.Error("HTMLString: %v", err)
  142. return
  143. }
  144. msg := NewMessage(u.Email(), c.Tr("mail.register_notify"), body)
  145. msg.Info = fmt.Sprintf("UID: %d, registration notify", u.ID())
  146. Send(msg)
  147. }
  148. // SendCollaboratorMail sends mail notification to new collaborator.
  149. func SendCollaboratorMail(u, doer User, repo Repository) {
  150. subject := fmt.Sprintf("%s added you to %s", doer.DisplayName(), repo.FullName())
  151. data := map[string]interface{}{
  152. "Subject": subject,
  153. "RepoName": repo.FullName(),
  154. "Link": repo.HTMLURL(),
  155. }
  156. body, err := render(MAIL_NOTIFY_COLLABORATOR, data)
  157. if err != nil {
  158. log.Error("HTMLString: %v", err)
  159. return
  160. }
  161. msg := NewMessage(u.Email(), subject, body)
  162. msg.Info = fmt.Sprintf("UID: %d, add collaborator", u.ID())
  163. Send(msg)
  164. }
  165. func composeTplData(subject, body, link string) map[string]interface{} {
  166. data := make(map[string]interface{}, 10)
  167. data["Subject"] = subject
  168. data["Body"] = body
  169. data["Link"] = link
  170. return data
  171. }
  172. func composeIssueMessages(issue Issue, repo Repository, doer User, tplName string, tos []string, info string) []*Message {
  173. subject := issue.MailSubject()
  174. body := string(markup.Markdown([]byte(issue.Content()), repo.HTMLURL(), repo.ComposeMetas()))
  175. data := composeTplData(subject, body, issue.HTMLURL())
  176. data["Doer"] = doer
  177. content, err := render(tplName, data)
  178. if err != nil {
  179. log.Error("HTMLString (%s): %v", tplName, err)
  180. }
  181. from := gomail.NewMessage().FormatAddress(setting.MailService.FromEmail, doer.DisplayName())
  182. msgs := make([]*Message, len(tos))
  183. for idx, to := range tos {
  184. msg := NewMessageFrom(to, from, subject, content)
  185. msg.Info = fmt.Sprintf("Subject: %s, %s", subject, info)
  186. msgs[idx] = msg
  187. }
  188. return msgs
  189. }
  190. // SendIssueCommentMail composes and sends issue comment emails to target receivers.
  191. func SendIssueCommentMail(issue Issue, repo Repository, doer User, tos []string) {
  192. if len(tos) == 0 {
  193. return
  194. }
  195. msgs := composeIssueMessages(issue, repo, doer, MAIL_ISSUE_COMMENT, tos, "issue comment")
  196. for _, msg := range msgs {
  197. Send(msg)
  198. }
  199. }
  200. // SendIssueMentionMail composes and sends issue mention emails to target receivers.
  201. func SendIssueMentionMail(issue Issue, repo Repository, doer User, tos []string) {
  202. if len(tos) == 0 {
  203. return
  204. }
  205. msgs := composeIssueMessages(issue, repo, doer, MAIL_ISSUE_MENTION, tos, "issue mention")
  206. for _, msg := range msgs {
  207. Send(msg)
  208. }
  209. }