Advertisement
Guest User

Untitled

a guest
Jul 15th, 2016
88
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.85 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. config *SESEmailConfig
  25. )
  26.  
  27. // Amazon SES email config
  28. type SESEmailConfig struct {
  29. smtpUsername string
  30. smtpPassword string
  31. host string
  32. port int
  33. }
  34.  
  35. func sendEmail(to []string, from, subject string, body []byte) error {
  36. m := gomail.NewMessage()
  37. m.SetHeader("From", from)
  38. m.SetHeader("To", to...)
  39. m.SetHeader("Subject", subject)
  40. m.SetBody("text/html", string(body))
  41. d := gomail.NewPlainDialer(config.host, config.port, config.smtpUsername, config.smtpPassword)
  42. return d.DialAndSend(m)
  43. }
  44.  
  45. func init() {
  46. config = &SESEmailConfig{
  47. smtpUsername: os.Getenv("SES_SMTP_USERNAME"),
  48. smtpPassword: os.Getenv("SES_SMTP_PASSWORD"),
  49. host: os.Getenv("SES_HOST"),
  50. port: 587,
  51. }
  52. }
  53.  
  54. func SendNewSignupEmailToAdmin(to []string, ctx map[string]string) error {
  55. body, err := templToBytes("signup", tmplNewSignup, ctx)
  56. if err != nil {
  57. return err
  58. }
  59. if err := sendEmail(to, fromEmail, NewSignupSubject, body); err != nil {
  60. return err
  61. }
  62. return nil
  63. }
  64.  
  65. func SendInvitationEmail(to []string, ctx map[string]string) error {
  66. body, err := templToBytes("invite", tmplInvite, ctx)
  67. if err != nil {
  68. return err
  69. }
  70. if err := sendEmail(to, fromEmail, InviteSubject, body); err != nil {
  71. return err
  72. }
  73. return nil
  74. }
  75.  
  76. func templToBytes(name, tmpl string, ctx map[string]string) ([]byte, error) {
  77. var buf bytes.Buffer
  78. t := template.Must(template.New(name).Parse(tmpl))
  79. if err := t.Execute(&buf, ctx); err != nil {
  80. return nil, err
  81. }
  82. return buf.Bytes(), nil
  83. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement