service.go 1.3 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576
  1. package mail
  2. import (
  3. "git.eugeniocarvalho.dev/eugeniucarvalho/apicodegen/api/errs"
  4. )
  5. type Destination struct {
  6. CcAddresses []*string
  7. ToAddresses []*string
  8. }
  9. type Body struct {
  10. Html *string
  11. Text *string
  12. }
  13. type Mail struct {
  14. Template *string
  15. Sender *string
  16. Subject *string
  17. Body *Body
  18. TemplateData interface{}
  19. Destination *Destination
  20. }
  21. type SendMailOptions struct {
  22. Adapter string
  23. Sync bool
  24. }
  25. type MailAdapter interface {
  26. Send(mail *Mail, options *SendMailOptions) (err *errs.Error)
  27. SendTemplateEmail(mail *Mail, options *SendMailOptions) (err *errs.Error)
  28. }
  29. type MailAdapters = map[string]MailAdapter
  30. var (
  31. Adapters = MailAdapters{}
  32. )
  33. func init(){
  34. Adapters["default"] = &AwsSESAdapter{}
  35. }
  36. func Send(mail *Mail, options *SendMailOptions) (err *errs.Error) {
  37. var (
  38. adapterID = "default"
  39. adapter MailAdapter
  40. found bool
  41. sendSync = true
  42. sendHandler func(mail *Mail, options *SendMailOptions) (err *errs.Error)
  43. )
  44. if options != nil {
  45. if options.Adapter != "" { adapterID = options.Adapter}
  46. if options.Sync { sendSync = options.Sync}
  47. }
  48. if adapter, found = Adapters[adapterID]; found {
  49. if mail.Template != nil {
  50. sendHandler = adapter.SendTemplateEmail
  51. } else {
  52. sendHandler = adapter.Send
  53. }
  54. if sendSync {
  55. err = sendHandler(mail, options)
  56. }else {
  57. go sendHandler(mail, options)
  58. }
  59. }
  60. return
  61. }