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.
104 lines
2.7 KiB
104 lines
2.7 KiB
package email
|
|
|
|
import (
|
|
"errors"
|
|
"fmt"
|
|
"strings"
|
|
|
|
"yunyan/lego/sys/log"
|
|
"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 newOptions(config map[string]interface{}, opts ...Option) Options {
|
|
options := Options{}
|
|
if config != nil {
|
|
mapstructure.Decode(config, &options)
|
|
}
|
|
for _, o := range opts {
|
|
o(&options)
|
|
}
|
|
if options.FromEmail == "" || options.Password == "" {
|
|
log.Panicf("start email Missing necessary configuration : Serverhost:%s Fromemail:%s Fompasswd:%s", options.FromEmail, options.EmailType)
|
|
}
|
|
return options
|
|
}
|
|
|
|
func newOptionsByOption(opts ...Option) Options {
|
|
options := Options{}
|
|
for _, o := range opts {
|
|
o(&options)
|
|
}
|
|
if options.FromEmail == "" || options.Password == "" {
|
|
log.Panicf("start email Missing necessary configuration : Serverhost:%s Fromemail:%s Fompasswd:%s", options.FromEmail, options.EmailType)
|
|
}
|
|
return options
|
|
}
|
|
|
|
// 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 与 newOptions 同构,但配置不合法时返回 error 而非 panic。
|
|
// 供运行时热重载(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()
|
|
}
|
|
|