Skip to content

Commit

Permalink
Add SMTP_FROM environment variable to set the sender email address
Browse files Browse the repository at this point in the history
  • Loading branch information
Chasnechok committed Apr 5, 2024
1 parent 194298b commit 2076ade
Show file tree
Hide file tree
Showing 2 changed files with 9 additions and 3 deletions.
11 changes: 8 additions & 3 deletions app/server/email/email.go
Original file line number Diff line number Diff line change
Expand Up @@ -57,18 +57,23 @@ func sendEmailViaSMTP(recipient, subject, htmlBody, textBody string) error {
smtpPort := os.Getenv("SMTP_PORT")
smtpUser := os.Getenv("SMTP_USER")
smtpPassword := os.Getenv("SMTP_PASSWORD")
smtpFrom := os.Getenv("SMTP_FROM")

if smtpHost == "" || smtpPort == "" || smtpUser == "" || smtpPassword == "" {
return fmt.Errorf("SMTP settings not found in environment variables")
}

if smtpFrom == "" {
smtpFrom = smtpUser
}

smtpAddress := fmt.Sprintf("%s:%s", smtpHost, smtpPort)

auth := smtp.PlainAuth("", smtpUser, smtpPassword, smtpHost)

// Generate a MIME boundary
boundary := "BOUNDARY1234567890"
header := fmt.Sprintf("From: %s\r\nTo: %s\r\nSubject: %s\r\nMIME-Version: 1.0\r\nContent-Type: multipart/alternative; boundary=\"%s\"\r\n\r\n", smtpUser, recipient, subject, boundary)
header := fmt.Sprintf("From: %s\r\nTo: %s\r\nSubject: %s\r\nMIME-Version: 1.0\r\nContent-Type: multipart/alternative; boundary=\"%s\"\r\n\r\n", smtpFrom, recipient, subject, boundary)

// Prepare the text body part
textPart := fmt.Sprintf("--%s\r\nContent-Type: text/plain; charset=\"UTF-8\"\r\n\r\n%s\r\n", boundary, textBody)
Expand All @@ -82,10 +87,10 @@ func sendEmailViaSMTP(recipient, subject, htmlBody, textBody string) error {
// Combine the parts to form the full email message
message := []byte(header + textPart + htmlPart + endBoundary)

err := smtp.SendMail(smtpAddress, auth, smtpUser, []string{recipient}, message)
err := smtp.SendMail(smtpAddress, auth, smtpFrom, []string{recipient}, message)
if err != nil {
return fmt.Errorf("error sending email via SMTP: %v", err)
}

return nil
}
}
1 change: 1 addition & 0 deletions guides/HOSTING.md
Original file line number Diff line number Diff line change
Expand Up @@ -11,6 +11,7 @@ export SMTP_HOST=smtp.example.com
export SMTP_PORT=587
export SMTP_USER=user
export SMTP_PASSWORD=password
export [email protected] # optional, if not set then SMTP_USER is used
```

Or, if you are using the `docker compose` option below, cp `app/_env` to `app/.env` and set the values in that file.
Expand Down

1 comment on commit 2076ade

@theone182
Copy link

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

good

Please sign in to comment.