52 lines
1012 B
Go
52 lines
1012 B
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
|
|
}
|