From 48a04fc6955c84f9d9f6d5bd0208d6bee34b2fe2 Mon Sep 17 00:00:00 2001 From: Rowan Seymour Date: Wed, 9 Sep 2020 10:17:22 -0500 Subject: [PATCH] Simplify test-smtp cmd using smtpx package --- cmd/test-smtp/main.go | 54 ++++++------------------------------------- 1 file changed, 7 insertions(+), 47 deletions(-) diff --git a/cmd/test-smtp/main.go b/cmd/test-smtp/main.go index 83a9a7395..be108dcc3 100644 --- a/cmd/test-smtp/main.go +++ b/cmd/test-smtp/main.go @@ -1,15 +1,13 @@ package main import ( - "net/url" - "strconv" - "github.com/nyaruka/ezconf" + "github.com/nyaruka/goflow/utils/smtpx" + "github.com/sirupsen/logrus" - "gopkg.in/mail.v2" ) -type Config struct { +type config struct { URL string `help:"the SMTP formatted URL to use to test sending"` To string `help:"the email address to send to"` Subject string `help:"the email subject to send"` @@ -18,7 +16,7 @@ type Config struct { func main() { // get our smtp server config - options := &Config{ + options := &config{ URL: "smtp://foo%40zap.com:opensesame@smtp.gmail.com:587/?from=foo%40zap.com&tls=true", To: "test@temba.io", Subject: "Test Email", @@ -31,52 +29,14 @@ func main() { ) loader.MustLoad() - // parse it - url, err := url.Parse(options.URL) + client, err := smtpx.NewClientFromURL(options.URL) if err != nil { logrus.WithError(err).Fatalf("unable to parse smtp config: %s", options.URL) } - // figure out our port - sPort := url.Port() - if sPort == "" { - sPort = "25" - } - port, err := strconv.Atoi(sPort) - if err != nil { - logrus.WithError(err).Fatalf("invalid port configuration: %s", options.URL) - } - - // and our user and password - if url.User == nil { - logrus.Fatalf("no user set for smtp server: %s", options.URL) - } - password, _ := url.User.Password() - - // get our from - from := url.Query()["from"] - if len(from) == 0 { - from = []string{url.User.Username()} - } - - // create our dialer for our org - d := mail.NewDialer(url.Hostname(), port, url.User.Username(), password) - - // send each of our emails, errors are logged but don't stop us from trying to send our other emails - m := mail.NewMessage() - m.SetHeader("From", from[0]) - m.SetHeader("To", options.To) - m.SetHeader("Subject", options.Subject) - m.SetBody("text/plain", options.Body) - - logrus.WithFields(logrus.Fields{ - "hostname": url.Hostname(), - "port": port, - "username": url.User.Username(), - "password": password, - }).Info("attempting to send email") + m := smtpx.NewMessage([]string{options.To}, options.Subject, options.Body, "") - err = d.DialAndSend(m) + err = smtpx.Send(client, m) if err != nil { logrus.WithError(err).Fatal("error sending email") }