You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

mail.go 11KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348
  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. "path"
  12. "regexp"
  13. "strings"
  14. texttmpl "text/template"
  15. "code.gitea.io/gitea/models"
  16. "code.gitea.io/gitea/modules/base"
  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!").Message)
  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 := path.Join(repo.Owner.Name, repo.Name)
  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 composeIssueCommentMessage(issue *models.Issue, doer *models.User, actionType models.ActionType, fromMention bool,
  132. content string, comment *models.Comment, tos []string, info string) *Message {
  133. if err := issue.LoadPullRequest(); err != nil {
  134. log.Error("LoadPullRequest: %v", err)
  135. return nil
  136. }
  137. var (
  138. subject string
  139. link string
  140. prefix string
  141. // Fall back subject for bad templates, make sure subject is never empty
  142. fallback string
  143. reviewComments []*models.Comment
  144. )
  145. commentType := models.CommentTypeComment
  146. if comment != nil {
  147. prefix = "Re: "
  148. commentType = comment.Type
  149. link = issue.HTMLURL() + "#" + comment.HashTag()
  150. } else {
  151. link = issue.HTMLURL()
  152. }
  153. reviewType := models.ReviewTypeComment
  154. if comment != nil && comment.Review != nil {
  155. reviewType = comment.Review.Type
  156. }
  157. fallback = prefix + fallbackMailSubject(issue)
  158. // This is the body of the new issue or comment, not the mail body
  159. body := string(markup.RenderByType(markdown.MarkupName, []byte(content), issue.Repo.HTMLURL(), issue.Repo.ComposeMetas()))
  160. actType, actName, tplName := actionToTemplate(issue, actionType, commentType, reviewType)
  161. if comment != nil && comment.Review != nil {
  162. reviewComments = make([]*models.Comment, 0, 10)
  163. for _, lines := range comment.Review.CodeComments {
  164. for _, comments := range lines {
  165. reviewComments = append(reviewComments, comments...)
  166. }
  167. }
  168. }
  169. mailMeta := map[string]interface{}{
  170. "FallbackSubject": fallback,
  171. "Body": body,
  172. "Link": link,
  173. "Issue": issue,
  174. "Comment": comment,
  175. "IsPull": issue.IsPull,
  176. "User": issue.Repo.MustOwner(),
  177. "Repo": issue.Repo.FullName(),
  178. "Doer": doer,
  179. "IsMention": fromMention,
  180. "SubjectPrefix": prefix,
  181. "ActionType": actType,
  182. "ActionName": actName,
  183. "ReviewComments": reviewComments,
  184. }
  185. var mailSubject bytes.Buffer
  186. if err := subjectTemplates.ExecuteTemplate(&mailSubject, string(tplName), mailMeta); err == nil {
  187. subject = sanitizeSubject(mailSubject.String())
  188. } else {
  189. log.Error("ExecuteTemplate [%s]: %v", string(tplName)+"/subject", err)
  190. }
  191. if subject == "" {
  192. subject = fallback
  193. }
  194. mailMeta["Subject"] = subject
  195. var mailBody bytes.Buffer
  196. if err := bodyTemplates.ExecuteTemplate(&mailBody, string(tplName), mailMeta); err != nil {
  197. log.Error("ExecuteTemplate [%s]: %v", string(tplName)+"/body", err)
  198. }
  199. msg := NewMessageFrom(tos, doer.DisplayName(), setting.MailService.FromEmail, subject, mailBody.String())
  200. msg.Info = fmt.Sprintf("Subject: %s, %s", subject, info)
  201. // Set Message-ID on first message so replies know what to reference
  202. if comment == nil {
  203. msg.SetHeader("Message-ID", "<"+issue.ReplyReference()+">")
  204. } else {
  205. msg.SetHeader("In-Reply-To", "<"+issue.ReplyReference()+">")
  206. msg.SetHeader("References", "<"+issue.ReplyReference()+">")
  207. }
  208. return msg
  209. }
  210. func sanitizeSubject(subject string) string {
  211. runes := []rune(strings.TrimSpace(subjectRemoveSpaces.ReplaceAllLiteralString(subject, " ")))
  212. if len(runes) > mailMaxSubjectRunes {
  213. runes = runes[:mailMaxSubjectRunes]
  214. }
  215. // Encode non-ASCII characters
  216. return mime.QEncoding.Encode("utf-8", string(runes))
  217. }
  218. // SendIssueCommentMail composes and sends issue comment emails to target receivers.
  219. func SendIssueCommentMail(issue *models.Issue, doer *models.User, actionType models.ActionType, content string, comment *models.Comment, tos []string) {
  220. if len(tos) == 0 {
  221. return
  222. }
  223. SendAsync(composeIssueCommentMessage(issue, doer, actionType, false, content, comment, tos, "issue comment"))
  224. }
  225. // SendIssueMentionMail composes and sends issue mention emails to target receivers.
  226. func SendIssueMentionMail(issue *models.Issue, doer *models.User, actionType models.ActionType, content string, comment *models.Comment, tos []string) {
  227. if len(tos) == 0 {
  228. return
  229. }
  230. SendAsync(composeIssueCommentMessage(issue, doer, actionType, true, content, comment, tos, "issue mention"))
  231. }
  232. // actionToTemplate returns the type and name of the action facing the user
  233. // (slightly different from models.ActionType) and the name of the template to use (based on availability)
  234. func actionToTemplate(issue *models.Issue, actionType models.ActionType,
  235. commentType models.CommentType, reviewType models.ReviewType) (typeName, name, template string) {
  236. if issue.IsPull {
  237. typeName = "pull"
  238. } else {
  239. typeName = "issue"
  240. }
  241. switch actionType {
  242. case models.ActionCreateIssue, models.ActionCreatePullRequest:
  243. name = "new"
  244. case models.ActionCommentIssue:
  245. name = "comment"
  246. case models.ActionCloseIssue, models.ActionClosePullRequest:
  247. name = "close"
  248. case models.ActionReopenIssue, models.ActionReopenPullRequest:
  249. name = "reopen"
  250. case models.ActionMergePullRequest:
  251. name = "merge"
  252. default:
  253. switch commentType {
  254. case models.CommentTypeReview:
  255. switch reviewType {
  256. case models.ReviewTypeApprove:
  257. name = "approve"
  258. case models.ReviewTypeReject:
  259. name = "reject"
  260. default:
  261. name = "review"
  262. }
  263. case models.CommentTypeCode:
  264. name = "code"
  265. case models.CommentTypeAssignees:
  266. name = "assigned"
  267. default:
  268. name = "default"
  269. }
  270. }
  271. template = typeName + "/" + name
  272. ok := bodyTemplates.Lookup(template) != nil
  273. if !ok && typeName != "issue" {
  274. template = "issue/" + name
  275. ok = bodyTemplates.Lookup(template) != nil
  276. }
  277. if !ok {
  278. template = typeName + "/default"
  279. ok = bodyTemplates.Lookup(template) != nil
  280. }
  281. if !ok {
  282. template = "issue/default"
  283. }
  284. return
  285. }
  286. // SendIssueAssignedMail composes and sends issue assigned email
  287. func SendIssueAssignedMail(issue *models.Issue, doer *models.User, content string, comment *models.Comment, tos []string) {
  288. SendAsync(composeIssueCommentMessage(issue, doer, models.ActionType(0), false, content, comment, tos, "issue assigned"))
  289. }