56 lines
1.4 KiB
Go
56 lines
1.4 KiB
Go
package biz
|
|
|
|
import (
|
|
"context"
|
|
"errors"
|
|
"strings"
|
|
)
|
|
|
|
type EmailRepo interface {
|
|
Send(context.Context, []string, string, string) error
|
|
DefaultRecipients() []string
|
|
Enabled() bool
|
|
}
|
|
|
|
type EmailUsecase struct{ repo EmailRepo }
|
|
|
|
func NewEmailUsecase(repo EmailRepo) *EmailUsecase { return &EmailUsecase{repo: repo} }
|
|
|
|
func splitRecipients(value string) []string {
|
|
parts := strings.Split(value, ",")
|
|
result := make([]string, 0, len(parts))
|
|
for _, part := range parts {
|
|
if recipient := strings.TrimSpace(part); recipient != "" {
|
|
result = append(result, recipient)
|
|
}
|
|
}
|
|
return result
|
|
}
|
|
|
|
func (uc *EmailUsecase) Send(ctx context.Context, to, subject, body string) error {
|
|
recipients := splitRecipients(to)
|
|
if len(recipients) == 0 || subject == "" {
|
|
return errors.New("收件人和邮件标题不能为空")
|
|
}
|
|
return uc.repo.Send(ctx, recipients, subject, body)
|
|
}
|
|
|
|
func (uc *EmailUsecase) Test(ctx context.Context) error {
|
|
recipients := uc.repo.DefaultRecipients()
|
|
if len(recipients) == 0 {
|
|
return errors.New("未配置测试邮件收件人")
|
|
}
|
|
return uc.repo.Send(ctx, recipients, "test", "test")
|
|
}
|
|
|
|
func (uc *EmailUsecase) Alert(ctx context.Context, subject, body string) error {
|
|
if !uc.repo.Enabled() {
|
|
return nil
|
|
}
|
|
recipients := uc.repo.DefaultRecipients()
|
|
if len(recipients) == 0 {
|
|
return nil
|
|
}
|
|
return uc.repo.Send(ctx, recipients, subject, body)
|
|
}
|