github.com/infraboard/keyauth@v0.8.1/apps/system/notify/mail/config.go (about) 1 package mail 2 3 import ( 4 "errors" 5 "fmt" 6 "strings" 7 8 "github.com/caarlos0/env/v6" 9 "github.com/infraboard/keyauth/apps/system/notify" 10 "github.com/infraboard/keyauth/common/tls" 11 ) 12 13 // LoadConfigFromEnv todo 14 func LoadConfigFromEnv() (*Config, error) { 15 cfg := &Config{TLSConfig: &tls.Config{}} 16 if err := env.Parse(cfg); err != nil { 17 return nil, fmt.Errorf("load config from env, %s", err.Error()) 18 } 19 return cfg, nil 20 } 21 22 // NewEmailConfig todo 23 func NewEmailConfig(host, user, pass string) *Config { 24 return &Config{ 25 Host: host, 26 AuthUserName: user, 27 AuthPassword: pass, 28 TLSConfig: &tls.Config{}, 29 } 30 } 31 32 // NewDefaultConfig todo 33 func NewDefaultConfig() *Config { 34 return &Config{ 35 TLSConfig: &tls.Config{}, 36 } 37 } 38 39 // Config todo 40 type Config struct { 41 Host string `bson:"host" json:"host" env:"K_EMAIL_HOST"` 42 AuthUserName string `bson:"username" json:"username" env:"K_EMAIL_USERNAME"` 43 AuthPassword string `bson:"password" json:"password,omitempty" env:"K_EMAIL_PASSWORD"` 44 AuthSecret string `bson:"secret" json:"secret,omitempty" env:"K_EMAIL_SECRET"` 45 AuthIdentity string `bson:"identity" json:"identity,omitempty" env:"K_EMAIL_IDENTITY"` 46 Hello string `bson:"hello" json:"hello,omitempty" env:"K_EMAIL_HELLO"` 47 From string `bson:"from" json:"from,omitempty" env:"K_EMAIL_FROM"` 48 SkipAuth bool `bson:"skip_auth" json:"skip_auth" env:"K_EMAIL_SKIP_AUTH"` 49 RequireTLS bool `bson:"require_tls" json:"require_tls" env:"K_EMAIL_REQUIRE_TLS"` 50 TLSConfig *tls.Config `bson:"tls_config" json:"tls_config"` 51 } 52 53 // Desensitize 脱敏 54 func (c *Config) Desensitize() { 55 c.AuthPassword = "" 56 c.AuthSecret = "" 57 } 58 59 // Validate todo 60 func (c *Config) Validate() error { 61 if c.Host == "" { 62 return errors.New("host, 邮件客户端服务器地址未配置") 63 } 64 65 if c.AuthUserName == "" { 66 return errors.New("username, 邮件发送用户未配置") 67 } 68 69 if !c.SkipAuth { 70 if c.AuthUserName == "" || c.AuthPassword == "" { 71 return errors.New("启用认证后, 需要配置用户名和密码(usernme, password)") 72 } 73 } 74 75 if c.From == "" { 76 c.From = fmt.Sprintf("%s<%s>", strings.Split(c.AuthUserName, "@")[0], c.AuthUserName) 77 } 78 79 return nil 80 } 81 82 // NewDeaultTestSendRequest todo 83 func NewDeaultTestSendRequest() *TestSendRequest { 84 return &TestSendRequest{ 85 SendMailRequest: notify.NewSendMailRequest(), 86 Config: NewDefaultConfig(), 87 } 88 } 89 90 // TestSendRequest todo 91 type TestSendRequest struct { 92 *notify.SendMailRequest 93 *Config 94 } 95 96 // Send todo 97 func (req *TestSendRequest) Send() error { 98 sd, err := NewSender(req.Config) 99 if err != nil { 100 return err 101 } 102 103 return sd.Send(req.SendMailRequest) 104 }