WIP: Full restruct, seprate service and api
Signed-off-by: Asai Neko <sugar@sne.moe>
This commit is contained in:
84
internal/email/email.go
Normal file
84
internal/email/email.go
Normal file
@@ -0,0 +1,84 @@
|
||||
package email
|
||||
|
||||
import (
|
||||
"crypto/tls"
|
||||
"errors"
|
||||
"strings"
|
||||
"time"
|
||||
|
||||
"github.com/spf13/viper"
|
||||
gomail "gopkg.in/gomail.v2"
|
||||
)
|
||||
|
||||
type Client struct {
|
||||
dialer *gomail.Dialer
|
||||
|
||||
host string
|
||||
port int
|
||||
username string
|
||||
security string
|
||||
insecure bool
|
||||
}
|
||||
|
||||
func (self *Client) NewSMTPClient() (*Client, error) {
|
||||
host := viper.GetString("email.host")
|
||||
port := viper.GetInt("email.port")
|
||||
user := viper.GetString("email.username")
|
||||
pass := viper.GetString("email.password")
|
||||
|
||||
security := strings.ToLower(viper.GetString("email.security"))
|
||||
insecure := viper.GetBool("email.insecure_skip_verify")
|
||||
|
||||
if host == "" || port == 0 || user == "" {
|
||||
return nil, errors.New("[Email] SMTP config not set")
|
||||
}
|
||||
|
||||
if pass == "" {
|
||||
return nil, errors.New("[Email] SMTP basic auth requires email.password")
|
||||
}
|
||||
|
||||
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("[Email] unknown smtp security mode: " + security)
|
||||
}
|
||||
|
||||
return &Client{
|
||||
dialer: dialer,
|
||||
host: host,
|
||||
port: port,
|
||||
username: user,
|
||||
security: security,
|
||||
insecure: insecure,
|
||||
}, nil
|
||||
}
|
||||
|
||||
func (c *Client) Send(from, to, subject, html string) (string, error) {
|
||||
if c.dialer == nil {
|
||||
return "", errors.New("[Email] SMTP dialer not initialized")
|
||||
}
|
||||
|
||||
m := gomail.NewMessage()
|
||||
m.SetHeader("From", 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
|
||||
}
|
||||
Reference in New Issue
Block a user