mailout/pkg/cmd/test.go
Thomas Maurice 09d3149932
All checks were successful
build / build (push) Successful in 1m10s
Build and release / build (push) Successful in 14m51s
feat(mail): adds a test subcomand
2024-02-13 18:30:54 +01:00

85 lines
1.9 KiB
Go

package cmd
import (
"crypto/tls"
"fmt"
"log"
"net/smtp"
"strings"
"github.com/sirupsen/logrus"
"github.com/spf13/cobra"
)
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"] = "This is a test email from the command line"
message := ""
for k, v := range headers {
message += fmt.Sprintf("%s: %s\r\n", k, v)
}
message += "\r\n"
message += "This is a test email message sent through the command line utility."
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")
},
}