Files
goodBaby/drivers/email/email.go
T

47 lines
1.1 KiB
Go
Raw Normal View History

2026-04-05 10:36:22 +08:00
package email
import (
2026-07-26 22:19:41 +08:00
"context"
"fmt"
2026-09-12 15:32:27 +08:00
"sort"
2026-07-26 22:19:41 +08:00
"strings"
"sync"
2026-04-05 10:36:22 +08:00
2026-09-12 15:32:27 +08:00
"github.com/ssdomei232/goodBaby/internal/retry"
2026-04-05 10:36:22 +08:00
)
2026-09-12 15:32:27 +08:00
// SendMail 用给定 SMTP 账号向规则配置里的所有地址发送邮件。
2026-07-26 22:19:41 +08:00
//
2026-09-12 15:32:27 +08:00
// 每个地址单独重试、互不阻塞;全部失败/部分失败都会汇总成错误返回,
2026-07-26 22:19:41 +08:00
// 由 runner 记录到执行日志中。
2026-09-12 15:32:27 +08:00
func SendMail(ctx context.Context, account *EmailAccountConfig, config *EmailRule) error {
2026-07-26 22:19:41 +08:00
var (
wg sync.WaitGroup
mu sync.Mutex
fails []string
)
2026-09-12 15:32:27 +08:00
for _, destination := range config.Destinations {
2026-07-26 22:19:41 +08:00
wg.Add(1)
go func(address string) {
defer wg.Done()
2026-09-12 15:32:27 +08:00
if err := retry.Do(ctx, func() error {
return sendMail(ctx, account, config, address)
}); err != nil {
2026-07-26 22:19:41 +08:00
mu.Lock()
fails = append(fails, fmt.Sprintf("%s: %v", address, err))
mu.Unlock()
}
}(destination)
}
wg.Wait()
if len(fails) > 0 {
2026-09-12 15:32:27 +08:00
// 并发发送的顺序不确定,排序后错误信息才是稳定的
sort.Strings(fails)
2026-07-26 22:19:41 +08:00
return fmt.Errorf("%d/%d 封邮件发送失败: %s",
2026-09-12 15:32:27 +08:00
len(fails), len(config.Destinations), strings.Join(fails, "; "))
2026-07-26 22:19:41 +08:00
}
return nil
2026-04-05 10:36:22 +08:00
}