Advertisement
Guest User

Untitled

a guest
Jul 15th, 2016
111
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.95 KB | None | 0 0
  1. package email
  2.  
  3. import (
  4. "bytes"
  5. "html/template"
  6. "os"
  7.  
  8. "gopkg.in/gomail.v2"
  9. )
  10.  
  11. const (
  12. tmplNewSignup = `
  13. New Signup with is done with email: {{.Email}}.
  14. `
  15. tmplInvite = `
  16. You have been invited to join awesome product. {{.InviteURL}}
  17. `
  18. )
  19.  
  20. var (
  21. NewSignupSubject = "New user signed up"
  22. InviteSubject = "You are being invited to awesome product"
  23. fromEmail = "aircto@launchyard.com"
  24. )
  25.  
  26. type EmailSender interface {
  27. SendEmail(to []string, from, subject string, body []byte) error
  28. }
  29.  
  30. var Sender EmailSender
  31.  
  32. // Amazon SES email sender
  33. type SESEmailSender struct {
  34. smtpUsername string
  35. smtpPassword string
  36. host string
  37. port int
  38. }
  39.  
  40. func (s *SESEmailSender) SendEmail(to []string, from, subject string, body []byte) error {
  41. m := gomail.NewMessage()
  42. m.SetHeader("From", from)
  43. m.SetHeader("To", to...)
  44. m.SetHeader("Subject", subject)
  45. m.SetBody("text/html", string(body))
  46. d := gomail.NewPlainDialer(s.host, s.port, s.smtpUsername, s.smtpPassword)
  47. return d.DialAndSend(m)
  48. }
  49.  
  50. func init() {
  51. Sender = &SESEmailSender{
  52. smtpUsername: os.Getenv("SES_SMTP_USERNAME"),
  53. smtpPassword: os.Getenv("SES_SMTP_PASSWORD"),
  54. host: os.Getenv("SES_HOST"),
  55. port: 587,
  56. }
  57. }
  58.  
  59. func SendNewSignupEmailToAdmin(to []string, ctx map[string]string) error {
  60. body, err := templToBytes("signup", tmplNewSignup, ctx)
  61. if err != nil {
  62. return err
  63. }
  64. if err := Sender.SendEmail(to, fromEmail, NewSignupSubject, body); err != nil {
  65. return err
  66. }
  67. return nil
  68. }
  69.  
  70. func SendInvitationEmail(to []string, ctx map[string]string) error {
  71. body, err := templToBytes("invite", tmplInvite, ctx)
  72. if err != nil {
  73. return err
  74. }
  75. if err := Sender.SendEmail(to, fromEmail, InviteSubject, body); err != nil {
  76. return err
  77. }
  78. return nil
  79. }
  80.  
  81. func templToBytes(name, tmpl string, ctx map[string]string) ([]byte, error) {
  82. var buf bytes.Buffer
  83. t := template.Must(template.New(name).Parse(tmpl))
  84. if err := t.Execute(&buf, ctx); err != nil {
  85. return nil, err
  86. }
  87. return buf.Bytes(), nil
  88. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement