email.go 6.1 KB

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