Skip to content

Commit

Permalink
feat: try StartTLS if SMTP server doesn't support pure TLS (#1676)
Browse files Browse the repository at this point in the history
* feat: try starttls if smtp server doesn't support pure tls

* chore: fix log id

* fix: errors.As is not working with own error type
  • Loading branch information
eliobischof committed Apr 28, 2021
1 parent 72f0cbe commit fd3ac0d
Showing 1 changed file with 28 additions and 6 deletions.
34 changes: 28 additions & 6 deletions internal/notification/providers/email/provider.go
Expand Up @@ -2,11 +2,13 @@ package email

import (
"crypto/tls"
"net"
"net/smtp"

"github.com/caos/logging"
caos_errs "github.com/caos/zitadel/internal/errors"
"github.com/caos/zitadel/internal/notification/providers"
"net"
"net/smtp"
"github.com/pkg/errors"
)

type Email struct {
Expand Down Expand Up @@ -93,31 +95,51 @@ func (smtpConfig SMTP) connectToSMTP(tlsRequired bool) (client *smtp.Client, err
func (smtpConfig SMTP) getSMPTClient() (*smtp.Client, error) {
client, err := smtp.Dial(smtpConfig.Host)
if err != nil {
return nil, caos_errs.ThrowInternal(err, "EMAIL-skwos", "Could not make smtp dial")
return nil, caos_errs.ThrowInternal(err, "EMAIL-skwos", "could not make smtp dial")
}
return client, nil
}

func (smtpConfig SMTP) getSMPTClientWithTls(host string) (*smtp.Client, error) {
conn, err := tls.Dial("tcp", smtpConfig.Host, &tls.Config{})

if errors.As(err, &tls.RecordHeaderError{}) {
logging.Log("MAIN-xKIzT").OnError(err).Warn("could not connect using normal tls. trying starttls instead...")
return smtpConfig.getSMPTClientWithStartTls(host)
}

if err != nil {
return nil, caos_errs.ThrowInternal(err, "EMAIL-sl39s", "Could not make tls dial")
return nil, caos_errs.ThrowInternal(err, "EMAIL-sl39s", "could not make tls dial")
}

client, err := smtp.NewClient(conn, host)
if err != nil {
return nil, caos_errs.ThrowInternal(err, "EMAIL-skwi4", "Could not create smtp client")
return nil, caos_errs.ThrowInternal(err, "EMAIL-skwi4", "could not create smtp client")
}
return client, err
}

func (smtpConfig SMTP) getSMPTClientWithStartTls(host string) (*smtp.Client, error) {
client, err := smtpConfig.getSMPTClient()
if err != nil {
return nil, err
}

if err := client.StartTLS(&tls.Config{
ServerName: host,
}); err != nil {
return nil, caos_errs.ThrowInternal(err, "EMAIL-guvsQ", "could not start tls")
}
return client, nil
}

func (smtpConfig SMTP) smtpAuth(client *smtp.Client, host string) error {
if !smtpConfig.HasAuth() {
return nil
}
// Auth
auth := smtp.PlainAuth("", smtpConfig.User, smtpConfig.Password, host)
err := client.Auth(auth)
logging.Log("EMAIL-s9kfs").WithField("smtp user", smtpConfig.User).OnError(err).Debug("Could not add smtp auth")
logging.Log("EMAIL-s9kfs").WithField("smtp user", smtpConfig.User).OnError(err).Debug("could not add smtp auth")
return err
}

0 comments on commit fd3ac0d

Please sign in to comment.