package mail import ( "crypto/tls" "github.com/astaxie/beego/logs" "gopkg.in/gomail.v2" settings2 "nginx-ui/server/modules/settings" "strconv" "strings" ) type Sender struct { Server string Port int Username string Password string Nickname string Ssl bool } func GetDefaultSender() *Sender { settings := settings2.GetSettings("email") sender := &Sender{} for _, v := range settings { k := v.ConfigKey if strings.HasSuffix(k, "@server") { sender.Server = v.ConfigValue } if strings.HasSuffix(k, "@port") { port, err := strconv.Atoi(v.ConfigValue) if err != nil { logs.Error("email port is invalid : %s, use 25 replace", v.ConfigValue) sender.Port = 25 } else { sender.Port = port } } if strings.HasSuffix(k, "@username") { sender.Username = v.ConfigValue } if strings.HasSuffix(k, "@password") { sender.Password = v.ConfigValue } if strings.HasSuffix(k, "@nickname") { sender.Nickname = v.ConfigValue } if strings.HasSuffix(k, "@ssl") { sender.Ssl = v.ConfigValue == "Y" } } return sender } func SendEmail(to string, subject string, body string, sender *Sender) error { if sender == nil { sender = GetDefaultSender() } d := gomail.NewDialer(sender.Server, sender.Port, sender.Username, sender.Password) d.TLSConfig = &tls.Config{InsecureSkipVerify: true} closer, err := d.Dial() if err != nil { logs.Error("dial error: %v", err) return err } defer closer.Close() m := gomail.NewMessage() from := m.FormatAddress(sender.Username, sender.Nickname) m.SetHeader("From", from) m.SetHeader("To", to) m.SetHeader("Subject", subject) m.SetBody("text/html", body) if err := d.DialAndSend(m); err != nil { logs.Error("send email error: %v", err) return err } return nil }