package email
import (
"context"
"encoding/base64"
"fmt"
"strings"
"donetick.com/core/config"
gomail "gopkg.in/gomail.v2"
)
type EmailSender struct {
client *gomail.Dialer
appHost string
}
func NewEmailSender(conf *config.Config) *EmailSender {
client := gomail.NewDialer(conf.EmailConfig.Host, conf.EmailConfig.Port, conf.EmailConfig.Email, conf.EmailConfig.Key)
// format conf.EmailConfig.Host and port :
// auth := smtp.PlainAuth("", conf.EmailConfig.Email, conf.EmailConfig.Password, host)
return &EmailSender{
client: client,
appHost: conf.EmailConfig.AppHost,
}
}
func (es *EmailSender) SendVerificationEmail(to, code string) error {
// msg := []byte(fmt.Sprintf("To: %s\r\nSubject: %s\r\n\r\n%s\r\n", to, subject, body))
msg := gomail.NewMessage()
msg.SetHeader("From", "no-reply@donetick.com")
msg.SetHeader("To", to)
msg.SetHeader("Subject", "Welcome to Donetick! Verifiy you email")
// text/html for a html email
htmlBody := `
Thank you for joining us. We're excited to have you on board.To complete your registration, click the button below
if you did not sign up with Donetick please Ignore this email.
Favoro LLC. All rights reserved
`
u := es.appHost + "/verify?c=" + encodeEmailAndCode(to, code)
htmlBody = strings.Replace(htmlBody, "{{verifyURL}}", u, 1)
msg.SetBody("text/html", htmlBody)
err := es.client.DialAndSend(msg)
if err != nil {
return err
}
return nil
}
func (es *EmailSender) SendResetPasswordEmail(c context.Context, to, code string) error {
msg := gomail.NewMessage()
msg.SetHeader("From", "no-reply@donetick.com")
msg.SetHeader("To", to)
msg.SetHeader("Subject", "Donetick! Password Reset")
htmlBody := `
Someone forgot their password 😔
We have received a password reset request for this email address. If you initiated this request, please click the button below to reset your password. Otherwise, you may safely ignore this email.
if you did not sign up with Donetick please Ignore this email.
Favoro LLC. All rights reserved
`
u := es.appHost + "/password/update?c=" + encodeEmailAndCode(to, code)
// logging.FromContext(c).Infof("Reset password URL: %s", u)
htmlBody = strings.Replace(htmlBody, "{{verifyURL}}", u, 1)
msg.SetBody("text/html", htmlBody)
err := es.client.DialAndSend(msg)
if err != nil {
return err
}
return nil
}
// func (es *EmailSender) SendFeedbackRequestEmail(to, code string) error {
// // msg := []byte(fmt.Sprintf("To: %s\r\nSubject: %s\r\n\r\n%s\r\n", to, subject, body))
// msg := gomail.NewMessage()
// }
func encodeEmailAndCode(email, code string) string {
data := email + ":" + code
return base64.StdEncoding.EncodeToString([]byte(data))
}
func DecodeEmailAndCode(encoded string) (string, string, error) {
data, err := base64.StdEncoding.DecodeString(encoded)
if err != nil {
return "", "", err
}
parts := string(data)
split := strings.Split(parts, ":")
if len(split) != 2 {
return "", "", fmt.Errorf("Invalid format")
}
return split[0], split[1], nil
}