added mail functionality

This commit is contained in:
$(pass /github/name)
2024-07-03 12:35:41 +02:00
parent 6d34d99835
commit 96f008d67e
10 changed files with 132 additions and 24 deletions

View File

@@ -0,0 +1,77 @@
package services
import (
"GoMembership/internal/models"
"GoMembership/pkg/logger"
"bytes"
"gopkg.in/gomail.v2"
"html/template"
)
type EmailService struct {
dialer *gomail.Dialer
adminEmail string
}
func NewEmailService(host string, port int, username, password, adminEmail string) *EmailService {
dialer := gomail.NewDialer(host, port, username, password)
return &EmailService{dialer: dialer, adminEmail: adminEmail}
}
func (s *EmailService) SendEmail(to string, subject string, body string) error {
msg := gomail.NewMessage()
msg.SetHeader("From", s.dialer.Username)
msg.SetHeader("To", to)
msg.SetHeader("Subject", subject)
msg.SetBody("text/html", body)
if err := s.dialer.DialAndSend(msg); err != nil {
logger.Error.Printf("Could not send email to %s: %v", to, err)
return err
}
logger.Info.Printf("Email sent to %s", to)
return nil
}
func ParseTemplate(path string, data interface{}) (string, error) {
// Read the email template file
tpl, err := template.ParseFiles(path)
if err != nil {
logger.Error.Printf("Failed to parse email template: %v", err)
return "", err
}
// Buffer to hold the rendered template
var tplBuffer bytes.Buffer
if err := tpl.Execute(&tplBuffer, data); err != nil {
logger.Error.Printf("Failed to execute email template: %v", err)
return "", err
}
return tplBuffer.String(), nil
}
func (s *EmailService) SendWelcomeEmail(user models.User) error {
// Prepare data to be injected into the template
data := struct {
FirstName string
LastName string
}{
FirstName: user.FirstName,
LastName: user.LastName,
}
subject := "Willkommen beim Dörpsmobil Hasloh e.V."
body, err := ParseTemplate("internal/templates/mail_welcome.html", data)
if err != nil {
logger.Error.Print("Couldn't send welcome mail")
return err
}
return s.SendEmail(user.Email, subject, body)
}
func (s *EmailService) NotifyAdminOfNewUser(userEmail string) error {
subject := "New User Registration"
body := "<p>A new user has registered with the email: " + userEmail + "</p>"
return s.SendEmail(s.adminEmail, subject, body)
}