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.
86 lines
2.1 KiB
86 lines
2.1 KiB
package email
|
|
|
|
import (
|
|
"errors"
|
|
"fmt"
|
|
"strings"
|
|
|
|
"yunyan/lego/utils/mapstructure"
|
|
)
|
|
|
|
type EmailType uint8
|
|
|
|
const (
|
|
QQEmail EmailType = iota //QQ邮箱
|
|
TencentEmail //腾讯企业邮箱
|
|
GmailEmail //Google邮箱
|
|
ResendEmail //Resend(HTTP API 发信,海外送达率优,Password 字段填 API Key)
|
|
|
|
)
|
|
|
|
type Option func(*Options)
|
|
type Options struct {
|
|
EmailType EmailType
|
|
FromEmail string
|
|
FromName string
|
|
Password string
|
|
}
|
|
|
|
func Set_EmailType(v EmailType) Option {
|
|
return func(o *Options) {
|
|
o.EmailType = v
|
|
}
|
|
}
|
|
|
|
func Set_FromEmail(v string) Option {
|
|
return func(o *Options) {
|
|
o.FromEmail = v
|
|
}
|
|
}
|
|
func Set_FromName(v string) Option {
|
|
return func(o *Options) {
|
|
o.FromName = v
|
|
}
|
|
}
|
|
func Set_Password(v string) Option {
|
|
return func(o *Options) {
|
|
o.Password = v
|
|
}
|
|
}
|
|
|
|
func newOptionsByOption(opts ...Option) (Options, error) {
|
|
options := Options{}
|
|
for _, o := range opts {
|
|
o(&options)
|
|
}
|
|
return options, options.validate()
|
|
}
|
|
|
|
// validate 校验发信必需字段。
|
|
// FromEmail 必须是「邮箱地址」而非域名:SMTP 与 Resend 的 from 都要求 name@domain 形式,
|
|
// 只填域名(如 mail.example.com)会被 Resend 以 422 validation_error 拒绝。
|
|
func (o Options) validate() error {
|
|
if o.FromEmail == "" {
|
|
return errors.New("email 配置缺失: FromEmail 为空")
|
|
}
|
|
if o.Password == "" {
|
|
return errors.New("email 配置缺失: Password 为空(SMTP 授权码 / Resend API Key)")
|
|
}
|
|
if !strings.Contains(o.FromEmail, "@") {
|
|
return fmt.Errorf("email 配置错误: FromEmail=%q 是域名不是邮箱地址(应形如 noreply@%s)", o.FromEmail, o.FromEmail)
|
|
}
|
|
return nil
|
|
}
|
|
|
|
// newOptionsChecked 解析 map 配置并校验,不合法时返回 error 而非 panic。
|
|
// 启动(OnInit)与运行时热重载(Reload)共用:配置缺失只应让本子系统降级/本次重载失败,不该打挂进程。
|
|
func newOptionsChecked(config map[string]interface{}, opts ...Option) (Options, error) {
|
|
options := Options{}
|
|
if config != nil {
|
|
mapstructure.Decode(config, &options)
|
|
}
|
|
for _, o := range opts {
|
|
o(&options)
|
|
}
|
|
return options, options.validate()
|
|
}
|
|
|