Skip to content

Commit

Permalink
Merge pull request #12 from perebaj/call_email_trigg
Browse files Browse the repository at this point in the history
✨ call email trigger
  • Loading branch information
perebaj authored Jan 23, 2024
2 parents 124f328 + dc64457 commit af4df7f
Show file tree
Hide file tree
Showing 2 changed files with 20 additions and 3 deletions.
17 changes: 17 additions & 0 deletions cmd/newsletter/main.go
Original file line number Diff line number Diff line change
Expand Up @@ -19,6 +19,7 @@ type Config struct {
LogLevel string
LogType string
Mongo mongodb.Config
Email newsletter.EmailConfig
}

func main() {
Expand All @@ -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)
Expand Down Expand Up @@ -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
}

Expand Down
6 changes: 3 additions & 3 deletions mail.go
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand All @@ -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)
}
Expand Down

0 comments on commit af4df7f

Please sign in to comment.