Vous ne pouvez pas sélectionner plus de 25 sujets Les noms de sujets doivent commencer par une lettre ou un nombre, peuvent contenir des tirets ('-') et peuvent comporter jusqu'à 35 caractères.

mail.go 10KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343
  1. // Copyright 2016 The Gogs Authors. All rights reserved.
  2. // Copyright 2019 The Gitea Authors. All rights reserved.
  3. // Use of this source code is governed by a MIT-style
  4. // license that can be found in the LICENSE file.
  5. package mailer
  6. import (
  7. "bytes"
  8. "fmt"
  9. "html/template"
  10. "mime"
  11. "regexp"
  12. "strings"
  13. texttmpl "text/template"
  14. "code.gitea.io/gitea/models"
  15. "code.gitea.io/gitea/modules/base"
  16. "code.gitea.io/gitea/modules/emoji"
  17. "code.gitea.io/gitea/modules/log"
  18. "code.gitea.io/gitea/modules/markup"
  19. "code.gitea.io/gitea/modules/markup/markdown"
  20. "code.gitea.io/gitea/modules/setting"
  21. "code.gitea.io/gitea/modules/timeutil"
  22. "gopkg.in/gomail.v2"
  23. )
  24. const (
  25. mailAuthActivate base.TplName = "auth/activate"
  26. mailAuthActivateEmail base.TplName = "auth/activate_email"
  27. mailAuthResetPassword base.TplName = "auth/reset_passwd"
  28. mailAuthRegisterNotify base.TplName = "auth/register_notify"
  29. mailNotifyCollaborator base.TplName = "notify/collaborator"
  30. // There's no actual limit for subject in RFC 5322
  31. mailMaxSubjectRunes = 256
  32. )
  33. var (
  34. bodyTemplates *template.Template
  35. subjectTemplates *texttmpl.Template
  36. subjectRemoveSpaces = regexp.MustCompile(`[\s]+`)
  37. )
  38. // InitMailRender initializes the mail renderer
  39. func InitMailRender(subjectTpl *texttmpl.Template, bodyTpl *template.Template) {
  40. subjectTemplates = subjectTpl
  41. bodyTemplates = bodyTpl
  42. }
  43. // SendTestMail sends a test mail
  44. func SendTestMail(email string) error {
  45. return gomail.Send(Sender, NewMessage([]string{email}, "Gitea Test Email!", "Gitea Test Email!").ToMessage())
  46. }
  47. // SendUserMail sends a mail to the user
  48. func SendUserMail(language string, u *models.User, tpl base.TplName, code, subject, info string) {
  49. data := map[string]interface{}{
  50. "DisplayName": u.DisplayName(),
  51. "ActiveCodeLives": timeutil.MinutesToFriendly(setting.Service.ActiveCodeLives, language),
  52. "ResetPwdCodeLives": timeutil.MinutesToFriendly(setting.Service.ResetPwdCodeLives, language),
  53. "Code": code,
  54. }
  55. var content bytes.Buffer
  56. if err := bodyTemplates.ExecuteTemplate(&content, string(tpl), data); err != nil {
  57. log.Error("Template: %v", err)
  58. return
  59. }
  60. msg := NewMessage([]string{u.Email}, subject, content.String())
  61. msg.Info = fmt.Sprintf("UID: %d, %s", u.ID, info)
  62. SendAsync(msg)
  63. }
  64. // Locale represents an interface to translation
  65. type Locale interface {
  66. Language() string
  67. Tr(string, ...interface{}) string
  68. }
  69. // SendActivateAccountMail sends an activation mail to the user (new user registration)
  70. func SendActivateAccountMail(locale Locale, u *models.User) {
  71. SendUserMail(locale.Language(), u, mailAuthActivate, u.GenerateActivateCode(), locale.Tr("mail.activate_account"), "activate account")
  72. }
  73. // SendResetPasswordMail sends a password reset mail to the user
  74. func SendResetPasswordMail(locale Locale, u *models.User) {
  75. SendUserMail(locale.Language(), u, mailAuthResetPassword, u.GenerateActivateCode(), locale.Tr("mail.reset_password"), "recover account")
  76. }
  77. // SendActivateEmailMail sends confirmation email to confirm new email address
  78. func SendActivateEmailMail(locale Locale, u *models.User, email *models.EmailAddress) {
  79. data := map[string]interface{}{
  80. "DisplayName": u.DisplayName(),
  81. "ActiveCodeLives": timeutil.MinutesToFriendly(setting.Service.ActiveCodeLives, locale.Language()),
  82. "Code": u.GenerateEmailActivateCode(email.Email),
  83. "Email": email.Email,
  84. }
  85. var content bytes.Buffer
  86. if err := bodyTemplates.ExecuteTemplate(&content, string(mailAuthActivateEmail), data); err != nil {
  87. log.Error("Template: %v", err)
  88. return
  89. }
  90. msg := NewMessage([]string{email.Email}, locale.Tr("mail.activate_email"), content.String())
  91. msg.Info = fmt.Sprintf("UID: %d, activate email", u.ID)
  92. SendAsync(msg)
  93. }
  94. // SendRegisterNotifyMail triggers a notify e-mail by admin created a account.
  95. func SendRegisterNotifyMail(locale Locale, u *models.User) {
  96. if setting.MailService == nil {
  97. log.Warn("SendRegisterNotifyMail is being invoked but mail service hasn't been initialized")
  98. return
  99. }
  100. data := map[string]interface{}{
  101. "DisplayName": u.DisplayName(),
  102. "Username": u.Name,
  103. }
  104. var content bytes.Buffer
  105. if err := bodyTemplates.ExecuteTemplate(&content, string(mailAuthRegisterNotify), data); err != nil {
  106. log.Error("Template: %v", err)
  107. return
  108. }
  109. msg := NewMessage([]string{u.Email}, locale.Tr("mail.register_notify"), content.String())
  110. msg.Info = fmt.Sprintf("UID: %d, registration notify", u.ID)
  111. SendAsync(msg)
  112. }
  113. // SendCollaboratorMail sends mail notification to new collaborator.
  114. func SendCollaboratorMail(u, doer *models.User, repo *models.Repository) {
  115. repoName := repo.FullName()
  116. subject := fmt.Sprintf("%s added you to %s", doer.DisplayName(), repoName)
  117. data := map[string]interface{}{
  118. "Subject": subject,
  119. "RepoName": repoName,
  120. "Link": repo.HTMLURL(),
  121. }
  122. var content bytes.Buffer
  123. if err := bodyTemplates.ExecuteTemplate(&content, string(mailNotifyCollaborator), data); err != nil {
  124. log.Error("Template: %v", err)
  125. return
  126. }
  127. msg := NewMessage([]string{u.Email}, subject, content.String())
  128. msg.Info = fmt.Sprintf("UID: %d, add collaborator", u.ID)
  129. SendAsync(msg)
  130. }
  131. func composeIssueCommentMessages(ctx *mailCommentContext, tos []string, fromMention bool, info string) []*Message {
  132. var (
  133. subject string
  134. link string
  135. prefix string
  136. // Fall back subject for bad templates, make sure subject is never empty
  137. fallback string
  138. reviewComments []*models.Comment
  139. )
  140. commentType := models.CommentTypeComment
  141. if ctx.Comment != nil {
  142. commentType = ctx.Comment.Type
  143. link = ctx.Issue.HTMLURL() + "#" + ctx.Comment.HashTag()
  144. } else {
  145. link = ctx.Issue.HTMLURL()
  146. }
  147. reviewType := models.ReviewTypeComment
  148. if ctx.Comment != nil && ctx.Comment.Review != nil {
  149. reviewType = ctx.Comment.Review.Type
  150. }
  151. // This is the body of the new issue or comment, not the mail body
  152. body := string(markup.RenderByType(markdown.MarkupName, []byte(ctx.Content), ctx.Issue.Repo.HTMLURL(), ctx.Issue.Repo.ComposeMetas()))
  153. actType, actName, tplName := actionToTemplate(ctx.Issue, ctx.ActionType, commentType, reviewType)
  154. if actName != "new" {
  155. prefix = "Re: "
  156. }
  157. fallback = prefix + fallbackMailSubject(ctx.Issue)
  158. if ctx.Comment != nil && ctx.Comment.Review != nil {
  159. reviewComments = make([]*models.Comment, 0, 10)
  160. for _, lines := range ctx.Comment.Review.CodeComments {
  161. for _, comments := range lines {
  162. reviewComments = append(reviewComments, comments...)
  163. }
  164. }
  165. }
  166. mailMeta := map[string]interface{}{
  167. "FallbackSubject": fallback,
  168. "Body": body,
  169. "Link": link,
  170. "Issue": ctx.Issue,
  171. "Comment": ctx.Comment,
  172. "IsPull": ctx.Issue.IsPull,
  173. "User": ctx.Issue.Repo.MustOwner(),
  174. "Repo": ctx.Issue.Repo.FullName(),
  175. "Doer": ctx.Doer,
  176. "IsMention": fromMention,
  177. "SubjectPrefix": prefix,
  178. "ActionType": actType,
  179. "ActionName": actName,
  180. "ReviewComments": reviewComments,
  181. }
  182. var mailSubject bytes.Buffer
  183. if err := subjectTemplates.ExecuteTemplate(&mailSubject, string(tplName), mailMeta); err == nil {
  184. subject = sanitizeSubject(mailSubject.String())
  185. } else {
  186. log.Error("ExecuteTemplate [%s]: %v", string(tplName)+"/subject", err)
  187. }
  188. if subject == "" {
  189. subject = fallback
  190. }
  191. subject = emoji.ReplaceAliases(subject)
  192. mailMeta["Subject"] = subject
  193. var mailBody bytes.Buffer
  194. if err := bodyTemplates.ExecuteTemplate(&mailBody, string(tplName), mailMeta); err != nil {
  195. log.Error("ExecuteTemplate [%s]: %v", string(tplName)+"/body", err)
  196. }
  197. // Make sure to compose independent messages to avoid leaking user emails
  198. msgs := make([]*Message, 0, len(tos))
  199. for _, to := range tos {
  200. msg := NewMessageFrom([]string{to}, ctx.Doer.DisplayName(), setting.MailService.FromEmail, subject, mailBody.String())
  201. msg.Info = fmt.Sprintf("Subject: %s, %s", subject, info)
  202. // Set Message-ID on first message so replies know what to reference
  203. if actName == "new" {
  204. msg.SetHeader("Message-ID", "<"+ctx.Issue.ReplyReference()+">")
  205. } else {
  206. msg.SetHeader("In-Reply-To", "<"+ctx.Issue.ReplyReference()+">")
  207. msg.SetHeader("References", "<"+ctx.Issue.ReplyReference()+">")
  208. }
  209. msgs = append(msgs, msg)
  210. }
  211. return msgs
  212. }
  213. func sanitizeSubject(subject string) string {
  214. runes := []rune(strings.TrimSpace(subjectRemoveSpaces.ReplaceAllLiteralString(subject, " ")))
  215. if len(runes) > mailMaxSubjectRunes {
  216. runes = runes[:mailMaxSubjectRunes]
  217. }
  218. // Encode non-ASCII characters
  219. return mime.QEncoding.Encode("utf-8", string(runes))
  220. }
  221. // SendIssueAssignedMail composes and sends issue assigned email
  222. func SendIssueAssignedMail(issue *models.Issue, doer *models.User, content string, comment *models.Comment, tos []string) {
  223. SendAsyncs(composeIssueCommentMessages(&mailCommentContext{
  224. Issue: issue,
  225. Doer: doer,
  226. ActionType: models.ActionType(0),
  227. Content: content,
  228. Comment: comment,
  229. }, tos, false, "issue assigned"))
  230. }
  231. // actionToTemplate returns the type and name of the action facing the user
  232. // (slightly different from models.ActionType) and the name of the template to use (based on availability)
  233. func actionToTemplate(issue *models.Issue, actionType models.ActionType,
  234. commentType models.CommentType, reviewType models.ReviewType) (typeName, name, template string) {
  235. if issue.IsPull {
  236. typeName = "pull"
  237. } else {
  238. typeName = "issue"
  239. }
  240. switch actionType {
  241. case models.ActionCreateIssue, models.ActionCreatePullRequest:
  242. name = "new"
  243. case models.ActionCommentIssue, models.ActionCommentPull:
  244. name = "comment"
  245. case models.ActionCloseIssue, models.ActionClosePullRequest:
  246. name = "close"
  247. case models.ActionReopenIssue, models.ActionReopenPullRequest:
  248. name = "reopen"
  249. case models.ActionMergePullRequest:
  250. name = "merge"
  251. default:
  252. switch commentType {
  253. case models.CommentTypeReview:
  254. switch reviewType {
  255. case models.ReviewTypeApprove:
  256. name = "approve"
  257. case models.ReviewTypeReject:
  258. name = "reject"
  259. default:
  260. name = "review"
  261. }
  262. case models.CommentTypeCode:
  263. name = "code"
  264. case models.CommentTypeAssignees:
  265. name = "assigned"
  266. case models.CommentTypePullPush:
  267. name = "push"
  268. default:
  269. name = "default"
  270. }
  271. }
  272. template = typeName + "/" + name
  273. ok := bodyTemplates.Lookup(template) != nil
  274. if !ok && typeName != "issue" {
  275. template = "issue/" + name
  276. ok = bodyTemplates.Lookup(template) != nil
  277. }
  278. if !ok {
  279. template = typeName + "/default"
  280. ok = bodyTemplates.Lookup(template) != nil
  281. }
  282. if !ok {
  283. template = "issue/default"
  284. }
  285. return
  286. }