Files

60 lines
1.4 KiB
Go
Raw Permalink Normal View History

package service
import (
"accounting-app/internal/config"
"fmt"
"net/smtp"
)
// EmailService handles email notifications
type EmailService struct {
host string
port int
username string
password string
from string
enabled bool
}
// NewEmailService creates a new EmailService instance
func NewEmailService(cfg *config.Config) *EmailService {
if cfg.SMTPHost == "" || cfg.SMTPUser == "" {
return &EmailService{enabled: false}
}
return &EmailService{
host: cfg.SMTPHost,
port: cfg.SMTPPort,
username: cfg.SMTPUser,
password: cfg.SMTPPassword,
from: cfg.SMTPFrom,
enabled: true,
}
}
// SendAllocationNotification sends an email notification for auto allocation
func (s *EmailService) SendAllocationNotification(to string, amount float64, ruleName string) error {
if !s.enabled || to == "" {
return nil
}
subject := "Auto Allocation Executed"
body := fmt.Sprintf("Your automatic allocation rule '%s' has been executed.\nAmount: %.2f", ruleName, amount)
// Simple text email
msg := []byte(fmt.Sprintf("To: %s\r\n"+
"From: %s\r\n"+
"Subject: %s\r\n"+
"Content-Type: text/plain; charset=UTF-8\r\n"+
"\r\n"+
"%s\r\n", to, s.from, subject, body))
auth := smtp.PlainAuth("", s.username, s.password, s.host)
addr := fmt.Sprintf("%s:%d", s.host, s.port)
if err := smtp.SendMail(addr, auth, s.from, []string{to}, msg); err != nil {
return fmt.Errorf("failed to send email: %w", err)
}
return nil
}