smtp.go 1.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263
  1. package providers
  2. import (
  3. "crypto/tls"
  4. "git.wenlab.co/joe/beaconfire"
  5. gomail "gopkg.in/gomail.v2"
  6. )
  7. const SMTP_NAME = "smtp"
  8. type OptionsSmtp struct {
  9. Host string
  10. Port int
  11. InsecureSkipVerify bool
  12. Username string
  13. Password string
  14. }
  15. type smtp struct {
  16. opt *OptionsSmtp
  17. }
  18. var _ beaconfire.BeaconFire = &smtp{}
  19. func NewSmtp(opt *OptionsSmtp) *smtp {
  20. return &smtp{
  21. opt: opt,
  22. }
  23. }
  24. func (c *smtp) Name() string {
  25. return SMTP_NAME
  26. }
  27. func (c *smtp) Send(bp *beaconfire.BeaconParam) error {
  28. if len(bp.To) <= 0 {
  29. return beaconfire.ErrNoReceiver
  30. }
  31. mail := gomail.NewMessage()
  32. mail.SetHeader("From", bp.From)
  33. mail.SetHeader("To", bp.To...)
  34. mail.SetHeader("Subject", bp.Title)
  35. inHtml := true // format == "html"
  36. content := bp.FormatHTML()
  37. if inHtml {
  38. mail.SetBody("text/html", content)
  39. } else {
  40. mail.SetBody("text/plain", bp.Content)
  41. }
  42. var d *gomail.Dialer
  43. if c.opt.Username != "" && c.opt.Password != "" {
  44. d = gomail.NewDialer(c.opt.Host, c.opt.Port, c.opt.Username, c.opt.Password)
  45. } else {
  46. d = &gomail.Dialer{Host: c.opt.Host, Port: c.opt.Port}
  47. }
  48. if c.opt.InsecureSkipVerify {
  49. d.TLSConfig = &tls.Config{InsecureSkipVerify: true}
  50. }
  51. return d.DialAndSend(mail)
  52. }