Skip to content

Commit

Permalink
Merge pull request #4 from OpenConceptConsulting/parse-to-body
Browse files Browse the repository at this point in the history
Parse "To" lines in the message itself. Fixes #3
  • Loading branch information
ian-kent committed Oct 6, 2015
2 parents 68340da + 5e40bfe commit 4a4992b
Showing 1 changed file with 19 additions and 5 deletions.
24 changes: 19 additions & 5 deletions cmd/cmd.go
Original file line number Diff line number Diff line change
@@ -1,18 +1,21 @@
package cmd

import (
"bytes"
"flag"
"fmt"
"io/ioutil"
"log"
"net/smtp"
"os"
"os/user"
"regexp"
"strings"

"github.com/ogier/pflag"
)

// Go runs the MailHog sendmail replacement.
func Go() {
smtpAddr := "localhost:1025"

Expand Down Expand Up @@ -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")
Expand Down

0 comments on commit 4a4992b

Please sign in to comment.