From dc64457390c70801beed4bbf43323aa3d51ebc41 Mon Sep 17 00:00:00 2001 From: jojo Date: Tue, 23 Jan 2024 18:05:22 -0300 Subject: [PATCH] :sparkles: call email trigger --- cmd/newsletter/main.go | 17 +++++++++++++++++ mail.go | 6 +++--- 2 files changed, 20 insertions(+), 3 deletions(-) diff --git a/cmd/newsletter/main.go b/cmd/newsletter/main.go index d7bdd5f..6fff3b2 100644 --- a/cmd/newsletter/main.go +++ b/cmd/newsletter/main.go @@ -19,6 +19,7 @@ type Config struct { LogLevel string LogType string Mongo mongodb.Config + Email newsletter.EmailConfig } func main() { @@ -29,6 +30,10 @@ func main() { Mongo: mongodb.Config{ URI: getEnvWithDefault("NL_MONGO_URI", ""), }, + Email: newsletter.EmailConfig{ + Password: getEnvWithDefault("NL_EMAIL_PASSWORD", ""), + Username: getEnvWithDefault("NL_EMAIL_USERNAME", ""), + }, } signalCh := make(chan os.Signal, 1) @@ -77,6 +82,18 @@ func main() { crawler.Run(ctx, storage, newsletter.Fetch) }() + mail := newsletter.NewMailClient(cfg.Email) + + go func() { + for range time.Tick(time.Duration(50) * time.Second) { + err := newsletter.EmailTrigger(ctx, storage, mail) + if err != nil { + slog.Error("error sending email", "error", err) + signalCh <- syscall.SIGTERM + } + } + }() + <-signalCh } diff --git a/mail.go b/mail.go index d8b10be..2400b8a 100644 --- a/mail.go +++ b/mail.go @@ -13,7 +13,7 @@ const SMTPServer = "smtp.gmail.com" // EmailConfig contains the necessary information to authenticate in the SMTP server type EmailConfig struct { Password string - UserName string + Username string } // MailClient is the client that sends emails @@ -35,14 +35,14 @@ type Email interface { // Send sends an email to the given destination func (m MailClient) Send(dest []string, bodyMessage string) error { - auth := smtp.PlainAuth("", m.cfg.UserName, m.cfg.Password, SMTPServer) + auth := smtp.PlainAuth("", m.cfg.Username, m.cfg.Password, SMTPServer) msg := []byte("To: " + dest[0] + "\r\n" + "Subject: Newsletter\r\n" + "\r\n" + bodyMessage + "\r\n") - err := smtp.SendMail(SMTPServer+":587", auth, m.cfg.UserName, dest, []byte(msg)) + err := smtp.SendMail(SMTPServer+":587", auth, m.cfg.Username, dest, []byte(msg)) if err != nil { return fmt.Errorf("error sending email: %v", err) }