This repository has been archived on 2025-08-09. You can view files and clone it. You cannot open issues or pull requests or push a commit.
Files
web-app-template/service/mail.go
Tim Wundenberg ec0e748e1f
Some checks failed
Build Docker Image / Explore-Gitea-Actions (push) Failing after 45s
chore: extract mail to it's own service
2024-09-27 23:21:37 +02:00

94 lines
2.0 KiB
Go

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
}