Skip to content

Commit

Permalink
Split SendWithTLS from SendWithStartTLS(#87)
Browse files Browse the repository at this point in the history
A bug was introduced in 27742b0 where, in the process of trying to add TLS support, broke the way the connection is set up since it still tried to use `STARTTLS` under the hood.

Fixes #71.
  • Loading branch information
SteelPhase authored May 31, 2020
1 parent 93c0018 commit 8694dac
Showing 1 changed file with 72 additions and 2 deletions.
74 changes: 72 additions & 2 deletions email.go
Original file line number Diff line number Diff line change
Expand Up @@ -538,8 +538,9 @@ func (e *Email) parseSender() (string, error) {
}
}

// SendWithTLS sends an email with an optional TLS config.
// This is helpful if you need to connect to a host that is used an untrusted
// SendWithTLS sends an email over tls with an optional TLS config.
//
// The TLS Config is helpful if you need to connect to a host that is used an untrusted
// certificate.
func (e *Email) SendWithTLS(addr string, a smtp.Auth, t *tls.Config) error {
// Merge the To, Cc, and Bcc fields
Expand Down Expand Up @@ -578,6 +579,75 @@ func (e *Email) SendWithTLS(addr string, a smtp.Auth, t *tls.Config) error {
if err = c.Hello("localhost"); err != nil {
return err
}

if a != nil {
if ok, _ := c.Extension("AUTH"); ok {
if err = c.Auth(a); err != nil {
return err
}
}
}
if err = c.Mail(sender); err != nil {
return err
}
for _, addr := range to {
if err = c.Rcpt(addr); err != nil {
return err
}
}
w, err := c.Data()
if err != nil {
return err
}
_, err = w.Write(raw)
if err != nil {
return err
}
err = w.Close()
if err != nil {
return err
}
return c.Quit()
}

// SendWithStartTLS sends an email over TLS using STARTTLS with an optional TLS config.
//
// The TLS Config is helpful if you need to connect to a host that is used an untrusted
// certificate.
func (e *Email) SendWithStartTLS(addr string, a smtp.Auth, t *tls.Config) error {
// Merge the To, Cc, and Bcc fields
to := make([]string, 0, len(e.To)+len(e.Cc)+len(e.Bcc))
to = append(append(append(to, e.To...), e.Cc...), e.Bcc...)
for i := 0; i < len(to); i++ {
addr, err := mail.ParseAddress(to[i])
if err != nil {
return err
}
to[i] = addr.Address
}
// Check to make sure there is at least one recipient and one "From" address
if e.From == "" || len(to) == 0 {
return errors.New("Must specify at least one From address and one To address")
}
sender, err := e.parseSender()
if err != nil {
return err
}
raw, err := e.Bytes()
if err != nil {
return err
}

// Taken from the standard library
// https://github.com/golang/go/blob/master/src/net/smtp/smtp.go#L328
c, err := smtp.Dial(addr)
if err != nil {
return err
}
defer c.Close()
if err = c.Hello("localhost"); err != nil {
return err
}
// Use TLS if available
if ok, _ := c.Extension("STARTTLS"); ok {
if err = c.StartTLS(t); err != nil {
Expand Down

0 comments on commit 8694dac

Please sign in to comment.