mail.go 1.7 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697
  1. package api
  2. import (
  3. "bytes"
  4. "crypto/tls"
  5. "errors"
  6. "html/template"
  7. gomail "gopkg.in/gomail.v2"
  8. )
  9. type Profile struct {
  10. Host string `json:"host" bson:"host"`
  11. Usuario string `json:"usuario" bson:"usuario"`
  12. Password string `json:"password" bson:"password"`
  13. Nome string `json:"nome" bson:"nome"`
  14. Porta int `json:"porta" bson:"porta"`
  15. }
  16. type Message struct {
  17. gomail.Message
  18. Template string
  19. Context interface{}
  20. }
  21. var (
  22. Serders = map[string]*Profile{}
  23. )
  24. func New() *Message {
  25. return &Message{Message: *gomail.NewMessage()}
  26. }
  27. func (t *Profile) GetFullNameAdrress() string {
  28. return t.Nome + " <" + t.Usuario + ">"
  29. }
  30. func RegisterSender(nome string, s *Profile) {
  31. Serders[nome] = s
  32. }
  33. func Sender(nome string) (*Profile, bool) {
  34. s, ok := Serders[nome]
  35. return s, ok
  36. }
  37. func Send(sender string, m *Message) error {
  38. var (
  39. s *Profile
  40. ok bool
  41. )
  42. if s, ok = Sender(sender); !ok {
  43. return errors.New("Perfil '" + sender + "' não exites")
  44. }
  45. dialer := gomail.NewDialer(s.Host, s.Porta, s.Usuario, s.Password)
  46. dialer.TLSConfig = &tls.Config{InsecureSkipVerify: true}
  47. if err := m.parseTemplate(); err != nil {
  48. return err
  49. }
  50. return dialer.DialAndSend(&m.Message)
  51. }
  52. func (t *Message) Send(sender string) error {
  53. return Send(sender, t)
  54. }
  55. func (t *Message) SetTemplate(filename string, ctx interface{}) {
  56. t.Template = filename
  57. t.Context = ctx
  58. }
  59. func (m *Message) parseTemplate() (err error) {
  60. var (
  61. t *template.Template
  62. buf *bytes.Buffer
  63. )
  64. if m.Template == "" {
  65. return nil
  66. }
  67. if t, err = template.ParseFiles(m.Template); err != nil {
  68. return err
  69. }
  70. buf = new(bytes.Buffer)
  71. if err = t.Execute(buf, m.Context); err != nil {
  72. return err
  73. }
  74. m.SetBody("text/html", buf.String())
  75. return nil
  76. }