mailer.go 1.8 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485
  1. package mailer
  2. import (
  3. "fmt"
  4. "net/smtp"
  5. "strings"
  6. "github.com/dmitriygnatenko/internal/interfaces"
  7. )
  8. type mailer struct {
  9. isEnabled bool
  10. host string
  11. port string
  12. user string
  13. password string
  14. }
  15. type mailerAuth struct {
  16. username string
  17. password string
  18. }
  19. func Init(env interfaces.IEnv) interfaces.IMailer {
  20. host := strings.TrimSpace(env.GetSMTPHost())
  21. port := strings.TrimSpace(env.GetSMTPPort())
  22. user := strings.TrimSpace(env.GetSMTPUser())
  23. password := strings.TrimSpace(env.GetSMTPPassword())
  24. if host == "" || port == "" || user == "" || password == "" {
  25. return &mailer{}
  26. }
  27. return &mailer{
  28. isEnabled: true,
  29. host: host,
  30. port: port,
  31. user: user,
  32. password: password,
  33. }
  34. }
  35. func (m mailer) Send(recipient string, subject string, text string) error {
  36. if !m.isEnabled {
  37. return nil
  38. }
  39. msg := []byte("To: " + recipient + "\r\n" +
  40. "From: " + m.user + "\r\n" +
  41. "Subject: " + subject + "\r\n" +
  42. "Content-Type: text/plain; charset=\"UTF-8\"" + "\n\r\n" +
  43. text + "\r\n")
  44. to := []string{recipient}
  45. auth := m.GetMailerAuth(m.user, m.password)
  46. return smtp.SendMail(m.host+":"+m.port, auth, m.user, to, msg)
  47. }
  48. func (m mailer) GetMailerAuth(username, password string) smtp.Auth {
  49. return &mailerAuth{username, password}
  50. }
  51. func (a *mailerAuth) Start(_ *smtp.ServerInfo) (string, []byte, error) {
  52. return "LOGIN", nil, nil
  53. }
  54. func (a *mailerAuth) Next(fromServer []byte, more bool) ([]byte, error) {
  55. command := string(fromServer)
  56. command = strings.TrimSpace(command)
  57. command = strings.TrimSuffix(command, ":")
  58. command = strings.ToLower(command)
  59. if more {
  60. if command == "username" {
  61. return []byte(fmt.Sprintf("%s", a.username)), nil
  62. }
  63. if command == "password" {
  64. return []byte(fmt.Sprintf("%s", a.password)), nil
  65. }
  66. return nil, fmt.Errorf("unexpected server challenge: %s", command)
  67. }
  68. return nil, nil
  69. }