service.go 1.8 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485
  1. package smtp
  2. import (
  3. "bytes"
  4. "embed"
  5. "fmt"
  6. "html/template"
  7. "net/smtp"
  8. "git.linuxforward.com/byom/byom-core/config"
  9. "github.com/sirupsen/logrus"
  10. )
  11. type Service struct {
  12. client *smtp.Client
  13. template *template.Template
  14. logger *logrus.Entry
  15. }
  16. //go:embed templates/invite.html
  17. var inviteTpl embed.FS
  18. type EmailData struct {
  19. Token string
  20. WorkspaceName string
  21. URL string
  22. }
  23. func NewService(cnf *config.Smtp) *Service {
  24. logger := logrus.WithField("core", "email")
  25. //mock the smtp client
  26. client := &smtp.Client{}
  27. //parse the email template
  28. tmpl, err := template.ParseFS(inviteTpl, "templates/invite.html")
  29. if err != nil {
  30. logger.WithError(err).Error("failed to parse email template")
  31. panic(err)
  32. }
  33. return &Service{
  34. logger: logger,
  35. client: client,
  36. template: tmpl,
  37. }
  38. }
  39. func (s *Service) SendEmail(to, subject, body string) error {
  40. s.logger.WithField("to", to).WithField("subject", subject).Info("sending email")
  41. //since we are not actually sending emails, we will just log the email
  42. s.logger.WithField("body", body).Info("email body")
  43. return nil
  44. }
  45. func (s *Service) SendInviteEmail(to, token, workspace string) error {
  46. var body bytes.Buffer
  47. data := EmailData{
  48. Token: token,
  49. WorkspaceName: workspace,
  50. URL: fmt.Sprintf("https://%s.domain.com/invite/%s", workspace, token),
  51. }
  52. if err := s.template.Execute(&body, data); err != nil {
  53. return fmt.Errorf("template execution failed: %w", err)
  54. }
  55. return s.SendEmail(to, "Join "+workspace+" workspace", body.String())
  56. }
  57. func (s *Service) Close() error {
  58. if s.client != nil {
  59. err := s.client.Close()
  60. if err != nil {
  61. s.logger.WithError(err).Error("failed to close SMTP client")
  62. return fmt.Errorf("close SMTP client: %w", err)
  63. }
  64. s.logger.Info("SMTP client closed successfully")
  65. }
  66. s.template = nil
  67. return nil
  68. }