优化结构
This commit is contained in:
@@ -36,16 +36,30 @@ func (r *emailRepo) email() *conf.AdminBackend_Email {
|
||||
}
|
||||
|
||||
func (r *emailRepo) Enabled() bool {
|
||||
config := r.email()
|
||||
return config != nil && config.Host != "" && config.From != "" && config.Secret != "" && config.Port > 0
|
||||
return emailEnabled(r.email())
|
||||
}
|
||||
|
||||
func (r *emailRepo) DefaultRecipients() []string {
|
||||
config := r.email()
|
||||
if config == nil {
|
||||
if config == nil || strings.TrimSpace(config.To) == "" {
|
||||
return nil
|
||||
}
|
||||
return []string{config.To}
|
||||
return []string{strings.TrimSpace(config.To)}
|
||||
}
|
||||
|
||||
func emailEnabled(config *conf.AdminBackend_Email) bool {
|
||||
return config != nil && strings.TrimSpace(config.Host) != "" &&
|
||||
strings.TrimSpace(config.From) != "" && strings.TrimSpace(config.Secret) != "" && config.Port > 0
|
||||
}
|
||||
|
||||
func normalizeRecipients(values []string) []string {
|
||||
result := make([]string, 0, len(values))
|
||||
for _, value := range values {
|
||||
if value = strings.TrimSpace(value); value != "" {
|
||||
result = append(result, value)
|
||||
}
|
||||
}
|
||||
return result
|
||||
}
|
||||
|
||||
func cleanHeader(value string) string {
|
||||
@@ -53,19 +67,23 @@ func cleanHeader(value string) string {
|
||||
}
|
||||
|
||||
func (r *emailRepo) Send(ctx context.Context, to []string, subject, body string) error {
|
||||
if !r.Enabled() {
|
||||
config := r.email()
|
||||
if !emailEnabled(config) {
|
||||
return errors.New("邮件服务未配置")
|
||||
}
|
||||
to = normalizeRecipients(to)
|
||||
if len(to) == 0 {
|
||||
return errors.New("收件人不能为空")
|
||||
}
|
||||
config := r.email()
|
||||
if ctx == nil {
|
||||
ctx = context.Background()
|
||||
}
|
||||
address := net.JoinHostPort(config.Host, fmt.Sprint(config.Port))
|
||||
dialer := &net.Dialer{Timeout: 10 * time.Second}
|
||||
var conn net.Conn
|
||||
var err error
|
||||
if config.IsSsl {
|
||||
conn, err = tls.DialWithDialer(dialer, "tcp", address, &tls.Config{ServerName: config.Host, MinVersion: tls.VersionTLS12})
|
||||
conn, err = (&tls.Dialer{NetDialer: dialer, Config: &tls.Config{ServerName: config.Host, MinVersion: tls.VersionTLS12}}).DialContext(ctx, "tcp", address)
|
||||
} else {
|
||||
conn, err = dialer.DialContext(ctx, "tcp", address)
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user