smtp.go 963 B

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152
  1. package smtp
  2. import (
  3. "errors"
  4. "fmt"
  5. "net/smtp"
  6. )
  7. type SMTP struct {
  8. config Config
  9. }
  10. func NewSMTP(c Config) (*SMTP, error) {
  11. if len(c.username) == 0 {
  12. return nil, errors.New("empty username")
  13. }
  14. if len(c.password) == 0 {
  15. return nil, errors.New("empty password")
  16. }
  17. if len(c.host) == 0 {
  18. c.host = defaultHost
  19. }
  20. if c.port == 0 {
  21. c.port = defaultPort
  22. }
  23. return &SMTP{config: c}, nil
  24. }
  25. func (s SMTP) Send(recipient string, subject string, content string, html bool) error {
  26. contentType := "text/plain"
  27. if html {
  28. contentType = "text/html"
  29. }
  30. msg := []byte("To: " + recipient + "\r\n" +
  31. "From: " + s.config.username + "\r\n" +
  32. "Subject: " + subject + "\r\n" +
  33. "Content-Type: " + contentType + "; charset=\"UTF-8\"" + "\n\r\n" +
  34. content + "\r\n")
  35. return smtp.SendMail(
  36. fmt.Sprintf("%s:%d", s.config.host, s.config.port),
  37. getAuth(s.config.username, s.config.password),
  38. s.config.username,
  39. []string{recipient},
  40. msg,
  41. )
  42. }