Last active
July 15, 2016 14:23
-
-
Save kavirajk/a2a460ec8c807e570f8b64e5468e6bf6 to your computer and use it in GitHub Desktop.
Send Email (cannot be mocked)
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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 = "[email protected]" | |
config *SESEmailConfig | |
) | |
// Amazon SES email config | |
type SESEmailConfig struct { | |
smtpUsername string | |
smtpPassword string | |
host string | |
port int | |
} | |
func 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(config.host, config.port, config.smtpUsername, config.smtpPassword) | |
return d.DialAndSend(m) | |
} | |
func init() { | |
config = &SESEmailConfig{ | |
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 := 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