95 lines
2.2 KiB
Go
95 lines
2.2 KiB
Go
package cmd
|
|
|
|
import (
|
|
"crypto/tls"
|
|
"fmt"
|
|
"log"
|
|
"net/smtp"
|
|
"strings"
|
|
|
|
"github.com/sirupsen/logrus"
|
|
"github.com/spf13/cobra"
|
|
)
|
|
|
|
var (
|
|
flagTestMessage string
|
|
flagTestMessageSubject string
|
|
)
|
|
|
|
var TestCmd = &cobra.Command{
|
|
Use: "test",
|
|
Short: "sends an email through the configured server",
|
|
Long: ``,
|
|
Args: cobra.ExactArgs(1),
|
|
Run: func(cmd *cobra.Command, args []string) {
|
|
if cfg.Test == nil {
|
|
logrus.Fatal("you need to specify a `test` config block")
|
|
}
|
|
|
|
tlsConfig := &tls.Config{
|
|
InsecureSkipVerify: true,
|
|
ServerName: strings.Split(cfg.Test.Address, ":")[0],
|
|
}
|
|
|
|
conn, err := tls.Dial("tcp", cfg.Test.Address, tlsConfig)
|
|
if err != nil {
|
|
log.Panic(err)
|
|
}
|
|
|
|
c, err := smtp.NewClient(conn, strings.Split(cfg.Test.Address, ":")[0])
|
|
if err != nil {
|
|
log.Panic(err)
|
|
}
|
|
|
|
headers := make(map[string]string)
|
|
headers["From"] = cfg.Test.Username
|
|
headers["To"] = args[0]
|
|
headers["Subject"] = flagTestMessageSubject
|
|
|
|
message := ""
|
|
for k, v := range headers {
|
|
message += fmt.Sprintf("%s: %s\r\n", k, v)
|
|
}
|
|
message += "\r\n"
|
|
|
|
message += flagTestMessage
|
|
|
|
auth := smtp.PlainAuth("", cfg.Test.Username, cfg.Test.Password, strings.Split(cfg.Test.Address, ":")[0])
|
|
|
|
if err = c.Auth(auth); err != nil {
|
|
logrus.WithError(err).Fatal("could not authenticate to server")
|
|
}
|
|
|
|
if err = c.Mail(cfg.Test.Username); err != nil {
|
|
logrus.WithError(err).Fatal("could not create email")
|
|
}
|
|
|
|
if err = c.Rcpt(args[0]); err != nil {
|
|
logrus.WithError(err).Fatal("could not set email destination")
|
|
}
|
|
|
|
w, err := c.Data()
|
|
if err != nil {
|
|
logrus.WithError(err).Fatal("could not set email data")
|
|
}
|
|
|
|
_, err = w.Write([]byte(message))
|
|
if err != nil {
|
|
logrus.WithError(err).Fatal("could not set email data")
|
|
}
|
|
|
|
err = w.Close()
|
|
if err != nil {
|
|
logrus.WithError(err).Fatal("close email")
|
|
}
|
|
|
|
c.Quit()
|
|
|
|
logrus.Info("sent test email")
|
|
},
|
|
}
|
|
|
|
func InitTestCmd() {
|
|
TestCmd.PersistentFlags().StringVarP(&flagTestMessage, "message", "m", "This is a test email message sent through the command line utility.", "What to send as a test message")
|
|
TestCmd.PersistentFlags().StringVarP(&flagTestMessageSubject, "subject", "s", "This is a test email from the command line", "What to send as a test message subject")
|
|
}
|