66 lines
1.4 KiB
Go

package models
import (
"fmt"
"github.com/go-mail/mail/v2"
)
type Email struct {
To string
Subject string
Text string
Html string
}
type EmailService struct {
DefaultSender string
dialer *mail.Dialer
}
func NewEmailService(host string, port int, username, pass, sender string) *EmailService {
es := EmailService{
dialer: mail.NewDialer(host, port, username, pass),
DefaultSender: sender,
}
return &es
}
func (es *EmailService) Send(email Email) error {
msg := mail.NewMessage()
msg.SetHeader("To", email.To)
msg.SetHeader("From", es.DefaultSender)
msg.SetHeader("Subject", email.Subject)
if email.Html != "" && email.Text != "" {
msg.SetBody("text/plain", email.Text)
msg.AddAlternative("text/html", email.Html)
} else if email.Text != "" {
msg.SetBody("text/plain", email.Text)
} else if email.Html != "" {
msg.SetBody("text/html", email.Html)
}
err := es.dialer.DialAndSend(msg)
if err != nil {
return fmt.Errorf("send: %w", err)
}
return nil
}
func (es *EmailService) SendPasswordReset(to, resetURL string) error {
email := Email{
Subject: "Reset your password",
To: to,
Text: "To reset your password, please visit the following link: " + resetURL,
Html: `<p>To reset your password, please visit the following link: <a href="` + resetURL + `">` + resetURL + `</a></p>`,
}
err := es.Send(email)
if err != nil {
return fmt.Errorf("forgot password email: %w", err)
}
return nil
}