chore: extract mail to it's own service
Some checks failed
Build Docker Image / Explore-Gitea-Actions (push) Failing after 45s
Some checks failed
Build Docker Image / Explore-Gitea-Actions (push) Failing after 45s
This commit is contained in:
93
service/mail.go
Normal file
93
service/mail.go
Normal file
@@ -0,0 +1,93 @@
|
||||
package service
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"log"
|
||||
"me-fit/utils"
|
||||
"net/smtp"
|
||||
"os"
|
||||
)
|
||||
|
||||
type ServiceMail interface {
|
||||
SendMail(to string, subject string, message string) error
|
||||
}
|
||||
|
||||
func NewServiceMail() ServiceMail {
|
||||
enabled := os.Getenv("SMTP_ENABLED") == "true"
|
||||
host := os.Getenv("SMTP_HOST")
|
||||
port := os.Getenv("SMTP_PORT")
|
||||
user := os.Getenv("SMTP_USER")
|
||||
pass := os.Getenv("SMTP_PASS")
|
||||
fromMail := os.Getenv("SMTP_FROM_MAIL")
|
||||
fromName := os.Getenv("SMTP_FROM_NAME")
|
||||
|
||||
if enabled {
|
||||
if host == "" {
|
||||
log.Fatal("SMTP_HOST must be set")
|
||||
}
|
||||
if port == "" {
|
||||
log.Fatal("SMTP_PORT must be set")
|
||||
}
|
||||
if user == "" {
|
||||
log.Fatal("SMTP_USER must be set")
|
||||
}
|
||||
if pass == "" {
|
||||
log.Fatal("SMTP_PASS must be set")
|
||||
}
|
||||
if fromMail == "" {
|
||||
log.Fatal("SMTP_FROM_MAIL must be set")
|
||||
}
|
||||
if fromName == "" {
|
||||
log.Fatal("SMTP_FROM_NAME must be set")
|
||||
}
|
||||
|
||||
return NewServiceMailSmtp(host, port, user, pass, fromMail, fromName)
|
||||
} else {
|
||||
if utils.Environment == "prod" {
|
||||
log.Fatal("SMTP_ENABLED must be set to true in production")
|
||||
}
|
||||
return NewServiceMailStub()
|
||||
}
|
||||
}
|
||||
|
||||
type ServiceMailSmtp struct {
|
||||
host string
|
||||
port string
|
||||
auth smtp.Auth
|
||||
fromMail string
|
||||
fromName string
|
||||
}
|
||||
|
||||
func NewServiceMailSmtp(
|
||||
host string,
|
||||
port string,
|
||||
user string,
|
||||
pass string,
|
||||
fromMail string,
|
||||
fromName string) ServiceMailSmtp {
|
||||
return ServiceMailSmtp{
|
||||
host: host,
|
||||
port: port,
|
||||
auth: smtp.PlainAuth("", user, pass, host),
|
||||
fromMail: fromMail,
|
||||
fromName: fromName,
|
||||
}
|
||||
}
|
||||
|
||||
func (service ServiceMailSmtp) SendMail(to string, subject string, message string) error {
|
||||
|
||||
msg := fmt.Sprintf("From: %v <%v>\nTo: %v\nSubject: %v\nMIME-version: 1.0;\nContent-Type: text/html; charset=\"UTF-8\";\n\n%v", service.fromName, service.fromMail, to, subject, message)
|
||||
|
||||
return smtp.SendMail(service.host+":"+service.port, service.auth, service.fromMail, []string{to}, []byte(msg))
|
||||
}
|
||||
|
||||
type ServiceMailStub struct {
|
||||
}
|
||||
|
||||
func NewServiceMailStub() ServiceMailStub {
|
||||
return ServiceMailStub{}
|
||||
}
|
||||
|
||||
func (service ServiceMailStub) SendMail(to string, subject string, message string) error {
|
||||
return nil
|
||||
}
|
||||
Reference in New Issue
Block a user