Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

✨ call email trigger #12

Merged
merged 1 commit into from
Jan 23, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
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