summaryrefslogtreecommitdiffstats
path: root/services/mailer/mail_admin_new_user.go
blob: 0713de8a9515d9a9af9e2d40031228303089600d (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
// Copyright 2023 The Forgejo Authors. All rights reserved.
// SPDX-License-Identifier: MIT
package mailer

import (
	"bytes"
	"context"
	"strconv"

	user_model "code.gitea.io/gitea/models/user"
	"code.gitea.io/gitea/modules/base"
	"code.gitea.io/gitea/modules/log"
	"code.gitea.io/gitea/modules/setting"
	"code.gitea.io/gitea/modules/templates"
	"code.gitea.io/gitea/modules/translation"
)

const (
	tplNewUserMail base.TplName = "notify/admin_new_user"
)

// MailNewUser sends notification emails on new user registrations to all admins
func MailNewUser(ctx context.Context, u *user_model.User) {
	if !setting.Admin.SendNotificationEmailOnNewUser {
		return
	}
	if setting.MailService == nil {
		// No mail service configured
		return
	}

	recipients, err := user_model.GetAllAdmins(ctx)
	if err != nil {
		log.Error("user_model.GetAllAdmins: %v", err)
		return
	}

	langMap := make(map[string][]string)
	for _, r := range recipients {
		langMap[r.Language] = append(langMap[r.Language], r.Email)
	}

	for lang, tos := range langMap {
		mailNewUser(ctx, u, lang, tos)
	}
}

func mailNewUser(_ context.Context, u *user_model.User, lang string, tos []string) {
	locale := translation.NewLocale(lang)

	manageUserURL := setting.AppURL + "admin/users/" + strconv.FormatInt(u.ID, 10)
	subject := locale.TrString("mail.admin.new_user.subject", u.Name)
	body := locale.TrString("mail.admin.new_user.text", manageUserURL)
	mailMeta := map[string]any{
		"NewUser":      u,
		"NewUserUrl":   u.HTMLURL(),
		"Subject":      subject,
		"Body":         body,
		"Language":     locale.Language(),
		"Locale":       locale,
		"SanitizeHTML": templates.SanitizeHTML,
	}

	var mailBody bytes.Buffer

	if err := bodyTemplates.ExecuteTemplate(&mailBody, string(tplNewUserMail), mailMeta); err != nil {
		log.Error("ExecuteTemplate [%s]: %v", string(tplNewUserMail)+"/body", err)
		return
	}

	msgs := make([]*Message, 0, len(tos))
	for _, to := range tos {
		msg := NewMessage(to, subject, mailBody.String())
		msg.Info = subject
		msgs = append(msgs, msg)
	}
	SendAsync(msgs...)
}