Skip to content

Commit

Permalink
Simplify test-smtp cmd using smtpx package
Browse files Browse the repository at this point in the history
  • Loading branch information
rowanseymour committed Sep 9, 2020
1 parent cda7028 commit 48a04fc
Showing 1 changed file with 7 additions and 47 deletions.
54 changes: 7 additions & 47 deletions cmd/test-smtp/main.go
Original file line number Diff line number Diff line change
@@ -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"`
Expand All @@ -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",
Expand All @@ -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")
}
Expand Down

0 comments on commit 48a04fc

Please sign in to comment.