Forráskód Böngészése

Split SendWithTLS from SendWithStartTLS(#87)

A bug was introduced in 27742b011ce59bee8fe7b7f1383449193a8e2c9f 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.
SteelPhase 5 éve
szülő
commit
8694daca3f
1 módosított fájl, 72 hozzáadás és 2 törlés
  1. 72 2
      email.go

+ 72 - 2
email.go

@@ -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
@@ -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 {