Files
cloud-services/pkg/smtpclient/smtp.go

62 lines
1.1 KiB
Go

package smtpclient
import (
"fmt"
"net/smtp"
"strings"
"github.com/pkg/errors"
)
var ErrAuthRequired = errors.New("auth required")
const CRLF = "\r\n"
const FromEmail = "no-reply@fiskerinc.com"
type SMTPInterface interface {
Auth(username string, password string)
Send(from string, to []string, subject string, body string) error
Close()
}
func NewSMTP(host string, port int) SMTPInterface {
return &SMTP{
Host: host,
Port: port,
}
}
type SMTP struct {
Host string
Port int
Username string
auth smtp.Auth
}
func (s *SMTP) Auth(username string, password string) {
s.auth = smtp.PlainAuth("", username, password, s.Host)
}
func (s *SMTP) Send(from string, to []string, subject string, body string) error {
if s.auth == nil {
return ErrAuthRequired
}
msg := []string{
fmt.Sprintf("From: %s", from),
fmt.Sprintf("To: %s", strings.Join(to, ", ")),
fmt.Sprintf("Subject: %s", subject),
"",
fmt.Sprintf("%s%s", body, CRLF),
}
addr := fmt.Sprintf("%s:%d", s.Host, s.Port)
return smtp.SendMail(addr, s.auth, from, to, []byte(strings.Join(msg, CRLF)))
}
func (s *SMTP) Close() {
s.Host = ""
s.Username = ""
s.auth = nil
}