email_writer.go 768 B

123456789101112131415161718192021222324252627282930313233343536373839404142
  1. package logger
  2. import (
  3. "bytes"
  4. "encoding/json"
  5. "errors"
  6. "git.dmitriygnatenko.ru/dima/go-common/smtp"
  7. )
  8. type EmailWriter struct {
  9. recipient string
  10. subject string
  11. smtp *smtp.SMTP
  12. }
  13. func NewEmailWriter(smtp *smtp.SMTP, recipient string, subject string) (*EmailWriter, error) {
  14. if len(recipient) == 0 {
  15. return nil, errors.New("empty recipient")
  16. }
  17. if smtp == nil {
  18. return nil, errors.New("empty smtp client")
  19. }
  20. return &EmailWriter{
  21. recipient: recipient,
  22. subject: subject,
  23. smtp: smtp,
  24. }, nil
  25. }
  26. func (w EmailWriter) Write(p []byte) (int, error) {
  27. var out bytes.Buffer
  28. if err := json.Indent(&out, p, "", " "); err != nil {
  29. return 0, err
  30. }
  31. err := w.smtp.Send(w.recipient, w.subject, out.String(), false)
  32. return 0, err
  33. }