zitadel/internal/notification/channels/smtp/channel.go
Miguel Cabrerizo d229da6af7
feat: SMTP Templates (#6932)
* feat: smtp templates poc

* feat: add isActive & ProviderType to SMTP backend

* feat: change providertype to uint32 and fix tests

* feat: minimal smtp provider component

* feat: woking on diiferent providers

* feat: keep working on providers

* feat: initial stepper for new provider

* fix: settings list and working on stepper

* feat: step 1 and 2 form inputs

* feat: starter for smtp test step

* fix: misspelled SMPT

* fix: remove tests for now

* feat: add tls toggle remove old google provider

* feat: working on add smtp and table

* fix: duplicated identifiers

* fix: settings list

* fix: add missing smtp config properties

* fix: add configID to smtp config table

* fix: working on listproviders

* feat: working in listSMTPConfigs

* fix: add count to listsmtpconfigs

* fix: getting empty results from listSMTPConfigs

* feat: table now shows real data

* fix: remaining styles for smtp-table

* fix: remove old notification-smtp-provider-component

* feat: delete smtp configuration

* feat: deactivate smtp config

* feat: replace isActive with state for smtp config

* feat: activate smtp config

* fix: remaining errors after main merge

* fix: list smtp providers panic and material mdc

* feat: refactor to only one provider component

* feat: current provider details view

* fix: refactor AddSMTPConfig and ChangeSMTPConfig

* fix: smtp config reduce issue

* fix: recover domain in NewIAMSMTPConfigWriteModel

* fix: add code needed by SetUpInstance

* fix: go tests and warn about passing context to InstanceAggregateFromWriteModel

* fix: i18n and add missing trans for fr, it, zh

* fix: add e2e tests

* docs: add smtp templates

* fix: remove provider_type, add description

* fix: remaining error from merge main

* fix: add @stebenz change for primary key

* fix: inactive placed after removed to prevent deleted configs to show as inactive

* fix: smtp provider id can be empty (migrated)

* feat: add mailchimp transactional template

* feat: add Brevo (Sendinblue) template

* feat: change brevo logo, add color to tls icon

* fix: queries use resourceowner, id must not be empty

* fix: deal with old smtp settings and tests

* fix: resourceOwner is the instanceID

* fix: remove aggregate_id, rename SMTPConfigByAggregateID with SMTPConfigActive

* fix: add tests for multiple configs with different IDs

* fix: conflict

* fix: remove notification-smtp-provider

* fix: add @peintnermax suggestions, rename module and fix e2e tests

* fix: remove material legacy modules

* fix: remove ctx as parameter for  InstanceAggregateFromWriteModel

* fix: add Id to SMTPConfigToPb

* fix:  change InstanceAggregateFromWriteModel to avoid linter errors

* fix import

* rm unused package-lock

* update yarn lock

---------

Co-authored-by: Elio Bischof <elio@zitadel.com>
Co-authored-by: Max Peintner <max@caos.ch>
Co-authored-by: Stefan Benz <46600784+stebenz@users.noreply.github.com>
2024-04-11 09:16:10 +02:00

164 lines
4.3 KiB
Go

package smtp
import (
"crypto/tls"
"errors"
"net"
"net/smtp"
"github.com/zitadel/logging"
"github.com/zitadel/zitadel/internal/notification/channels"
"github.com/zitadel/zitadel/internal/notification/messages"
"github.com/zitadel/zitadel/internal/zerrors"
)
var _ channels.NotificationChannel = (*Email)(nil)
type Email struct {
smtpClient *smtp.Client
senderAddress string
senderName string
replyToAddress string
}
func InitChannel(cfg *Config) (*Email, error) {
client, err := cfg.SMTP.connectToSMTP(cfg.Tls)
if err != nil {
logging.New().WithError(err).Error("could not connect to smtp")
return nil, err
}
logging.New().Debug("successfully initialized smtp email channel")
return &Email{
smtpClient: client,
senderName: cfg.FromName,
senderAddress: cfg.From,
replyToAddress: cfg.ReplyToAddress,
}, nil
}
func (email *Email) HandleMessage(message channels.Message) error {
defer email.smtpClient.Close()
emailMsg, ok := message.(*messages.Email)
if !ok {
return zerrors.ThrowInternal(nil, "EMAIL-s8JLs", "message is not EmailMessage")
}
if emailMsg.Content == "" || emailMsg.Subject == "" || len(emailMsg.Recipients) == 0 {
return zerrors.ThrowInternalf(nil, "EMAIL-zGemZ", "subject, recipients and content must be set but got subject %s, recipients length %d and content length %d", emailMsg.Subject, len(emailMsg.Recipients), len(emailMsg.Content))
}
emailMsg.SenderEmail = email.senderAddress
emailMsg.SenderName = email.senderName
emailMsg.ReplyToAddress = email.replyToAddress
// To && From
if err := email.smtpClient.Mail(emailMsg.SenderEmail); err != nil {
return zerrors.ThrowInternalf(err, "EMAIL-s3is3", "could not set sender: %v", emailMsg.SenderEmail)
}
for _, recp := range append(append(emailMsg.Recipients, emailMsg.CC...), emailMsg.BCC...) {
if err := email.smtpClient.Rcpt(recp); err != nil {
return zerrors.ThrowInternalf(err, "EMAIL-s4is4", "could not set recipient: %v", recp)
}
}
// Data
w, err := email.smtpClient.Data()
if err != nil {
return err
}
content, err := emailMsg.GetContent()
if err != nil {
return err
}
_, err = w.Write([]byte(content))
if err != nil {
return err
}
err = w.Close()
if err != nil {
return err
}
return email.smtpClient.Quit()
}
func (smtpConfig SMTP) connectToSMTP(tlsRequired bool) (client *smtp.Client, err error) {
host, _, err := net.SplitHostPort(smtpConfig.Host)
if err != nil {
return nil, zerrors.ThrowInternal(err, "EMAIL-spR56", "could not split host and port for connect to smtp")
}
if !tlsRequired {
client, err = smtpConfig.getSMTPClient()
} else {
client, err = smtpConfig.getSMTPClientWithTls(host)
}
if err != nil {
return nil, err
}
err = smtpConfig.smtpAuth(client, host)
if err != nil {
return nil, err
}
return client, nil
}
func (smtpConfig SMTP) getSMTPClient() (*smtp.Client, error) {
client, err := smtp.Dial(smtpConfig.Host)
if err != nil {
return nil, zerrors.ThrowInternal(err, "EMAIL-skwos", "could not make smtp dial")
}
return client, nil
}
func (smtpConfig SMTP) getSMTPClientWithTls(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.getSMTPClientWithStartTls(host)
}
if err != nil {
return nil, zerrors.ThrowInternal(err, "EMAIL-sl39s", "could not make tls dial")
}
client, err := smtp.NewClient(conn, host)
if err != nil {
return nil, zerrors.ThrowInternal(err, "EMAIL-skwi4", "could not create smtp client")
}
return client, err
}
func (smtpConfig SMTP) getSMTPClientWithStartTls(host string) (*smtp.Client, error) {
client, err := smtpConfig.getSMTPClient()
if err != nil {
return nil, err
}
if err := client.StartTLS(&tls.Config{
ServerName: host,
}); err != nil {
return nil, zerrors.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 := unencryptedAuth{
smtp.PlainAuth("", smtpConfig.User, smtpConfig.Password, host),
}
err := client.Auth(auth)
if err != nil {
return zerrors.ThrowInternalf(err, "EMAIL-s9kfs", "could not add smtp auth for user %s", smtpConfig.User)
}
return nil
}