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 := `
 
 
` 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 := `
 
 
` 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 }