Skip to content

Instantly share code, notes, and snippets.

@kavirajk
Last active July 15, 2016 14:13
Show Gist options
  • Save kavirajk/17a996b67c729989e1cf9ea3ead4bea3 to your computer and use it in GitHub Desktop.
Save kavirajk/17a996b67c729989e1cf9ea3ead4bea3 to your computer and use it in GitHub Desktop.
Send Email (can be mocked)
package email
import (
"bytes"
"html/template"
"os"
"gopkg.in/gomail.v2"
)
const (
tmplNewSignup = `
New Signup with is done with email: {{.Email}}.
`
tmplInvite = `
You have been invited to join awesome product. {{.InviteURL}}
`
)
var (
NewSignupSubject = "New user signed up"
InviteSubject = "You are being invited to awesome product"
fromEmail = "aircto@launchyard.com"
)
type EmailSender interface {
SendEmail(to []string, from, subject string, body []byte) error
}
var Sender EmailSender
// Amazon SES email sender
type SESEmailSender struct {
smtpUsername string
smtpPassword string
host string
port int
}
func (s *SESEmailSender) SendEmail(to []string, from, subject string, body []byte) error {
m := gomail.NewMessage()
m.SetHeader("From", from)
m.SetHeader("To", to...)
m.SetHeader("Subject", subject)
m.SetBody("text/html", string(body))
d := gomail.NewPlainDialer(s.host, s.port, s.smtpUsername, s.smtpPassword)
return d.DialAndSend(m)
}
func init() {
Sender = &SESEmailSender{
smtpUsername: os.Getenv("SES_SMTP_USERNAME"),
smtpPassword: os.Getenv("SES_SMTP_PASSWORD"),
host: os.Getenv("SES_HOST"),
port: 587,
}
}
func SendInvitationEmail(to []string, ctx map[string]string) error {
body, err := templToBytes("invite", tmplInvite, ctx)
if err != nil {
return err
}
if err := Sender.SendEmail(to, fromEmail, InviteSubject, body); err != nil {
return err
}
return nil
}
func templToBytes(name, tmpl string, ctx map[string]string) ([]byte, error) {
var buf bytes.Buffer
t := template.Must(template.New(name).Parse(tmpl))
if err := t.Execute(&buf, ctx); err != nil {
return nil, err
}
return buf.Bytes(), nil
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment