diff --git a/cmd/cmd.go b/cmd/cmd.go index 5f2f482..6673bac 100644 --- a/cmd/cmd.go +++ b/cmd/cmd.go @@ -1,6 +1,7 @@ package cmd import ( + "bytes" "flag" "fmt" "io/ioutil" @@ -8,11 +9,13 @@ import ( "net/smtp" "os" "os/user" + "regexp" "strings" "github.com/ogier/pflag" ) +// Go runs the MailHog sendmail replacement. func Go() { smtpAddr := "localhost:1025" @@ -55,17 +58,28 @@ func Go() { recip = pflag.Args() } - if len(recip) == 0 { - fmt.Fprintln(os.Stderr, "missing recipient") - os.Exit(10) - } - body, err := ioutil.ReadAll(os.Stdin) if err != nil { fmt.Fprintln(os.Stderr, "error reading stdin") os.Exit(11) } + if len(recip) == 0 { + // We only need to parse the message to get a recipient if none where + // provided on the command line. + re := regexp.MustCompile("(?im)^To: (.*)\r\n$") + n := bytes.IndexByte(body, 0) + bodyStr := string(body[:n]) + includedRecip := re.FindAllString(bodyStr, -1) + if includedRecip == nil { + fmt.Fprintln(os.Stderr, "missing recipient") + os.Exit(10) + } + newRecip := make([]string, len(recip), len(recip)+len(includedRecip)+1) + copy(newRecip, recip) + recip = append(newRecip, includedRecip...) + } + err = smtp.SendMail(smtpAddr, nil, fromAddr, recip, body) if err != nil { fmt.Fprintln(os.Stderr, "error sending mail")