smtp.go 1.3 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364
  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. To []string
  15. }
  16. type smtp struct {
  17. opt *OptionsSmtp
  18. }
  19. var _ beaconfire.BeaconFire = &smtp{}
  20. func NewSmtp(opt *OptionsSmtp) *smtp {
  21. return &smtp{
  22. opt: opt,
  23. }
  24. }
  25. func (c *smtp) Name() string {
  26. return SMTP_NAME
  27. }
  28. func (c *smtp) Send(bp *beaconfire.BeaconParam) error {
  29. if len(c.opt.To) <= 0 {
  30. return beaconfire.ErrNoReceiver
  31. }
  32. mail := gomail.NewMessage()
  33. mail.SetHeader("From", c.opt.Username)
  34. mail.SetHeader("To", c.opt.To...)
  35. mail.SetHeader("Subject", bp.Title)
  36. inHtml := true // format == "html"
  37. content := bp.FormatHTML()
  38. if inHtml {
  39. mail.SetBody("text/html", content)
  40. } else {
  41. mail.SetBody("text/plain", bp.Content)
  42. }
  43. var d *gomail.Dialer
  44. if c.opt.Username != "" && c.opt.Password != "" {
  45. d = gomail.NewDialer(c.opt.Host, c.opt.Port, c.opt.Username, c.opt.Password)
  46. } else {
  47. d = &gomail.Dialer{Host: c.opt.Host, Port: c.opt.Port}
  48. }
  49. if c.opt.InsecureSkipVerify {
  50. d.TLSConfig = &tls.Config{InsecureSkipVerify: true}
  51. }
  52. return d.DialAndSend(mail)
  53. }