71 lines
1.4 KiB
Go
71 lines
1.4 KiB
Go
package email
|
|
|
|
import (
|
|
"crypto/tls"
|
|
"errors"
|
|
"strings"
|
|
"time"
|
|
|
|
"github.com/spf13/viper"
|
|
gomail "gopkg.in/gomail.v2"
|
|
)
|
|
|
|
type Client struct {
|
|
dialer *gomail.Dialer
|
|
from string
|
|
}
|
|
|
|
func NewSMTPClient() (*Client, error) {
|
|
host := viper.GetString("email.host")
|
|
port := viper.GetInt("email.port")
|
|
user := viper.GetString("email.username")
|
|
pass := viper.GetString("email.password")
|
|
from := viper.GetString("email.from")
|
|
|
|
security := strings.ToLower(viper.GetString("email.security"))
|
|
insecure := viper.GetBool("email.insecure_skip_verify")
|
|
|
|
if host == "" || port == 0 || user == "" || pass == "" {
|
|
return nil, errors.New("SMTP config not set")
|
|
}
|
|
|
|
dialer := gomail.NewDialer(host, port, user, pass)
|
|
|
|
dialer.TLSConfig = &tls.Config{
|
|
ServerName: host,
|
|
InsecureSkipVerify: insecure,
|
|
}
|
|
|
|
switch security {
|
|
case "ssl":
|
|
dialer.SSL = true
|
|
case "starttls":
|
|
dialer.SSL = false
|
|
case "plain", "":
|
|
dialer.SSL = false
|
|
dialer.TLSConfig = nil
|
|
default:
|
|
return nil, errors.New("unknown smtp security mode: " + security)
|
|
}
|
|
|
|
return &Client{
|
|
dialer: dialer,
|
|
from: from,
|
|
}, nil
|
|
}
|
|
|
|
func (c *Client) Send(to, subject, html string) (string, error) {
|
|
m := gomail.NewMessage()
|
|
|
|
m.SetHeader("From", c.from)
|
|
m.SetHeader("To", to)
|
|
m.SetHeader("Subject", subject)
|
|
m.SetBody("text/html", html)
|
|
|
|
if err := c.dialer.DialAndSend(m); err != nil {
|
|
return "", err
|
|
}
|
|
|
|
return time.Now().Format(time.RFC3339Nano), nil
|
|
}
|