package mailer import ( "context" "fmt" "net/smtp" "strings" "haixun-backend/internal/config" ) type Mailer interface { Send(ctx context.Context, to, subject, text string) error } type SMTPMailer struct { host string port int username string password string from string } func NewSMTPMailer(cfg config.SMTPConf) *SMTPMailer { if strings.TrimSpace(cfg.Host) == "" || strings.TrimSpace(cfg.From) == "" { return nil } return &SMTPMailer{host: cfg.Host, port: cfg.Port, username: cfg.Username, password: cfg.Password, from: cfg.From} } func (m *SMTPMailer) Send(ctx context.Context, to, subject, text string) error { if m == nil { return nil } select { case <-ctx.Done(): return ctx.Err() default: } addr := fmt.Sprintf("%s:%d", m.host, m.port) headers := []string{ "From: " + m.from, "To: " + to, "Subject: " + subject, "MIME-Version: 1.0", "Content-Type: text/plain; charset=UTF-8", } msg := strings.Join(headers, "\r\n") + "\r\n\r\n" + text var auth smtp.Auth if m.username != "" || m.password != "" { auth = smtp.PlainAuth("", m.username, m.password, m.host) } return smtp.SendMail(addr, auth, m.from, []string{to}, []byte(msg)) }