72 lines
1.2 KiB
Go
72 lines
1.2 KiB
Go
package main
|
|
|
|
import (
|
|
"fmt"
|
|
"os"
|
|
|
|
"github.com/wneessen/go-mail"
|
|
)
|
|
|
|
type MailClient struct {
|
|
client *mail.Client
|
|
}
|
|
|
|
type TestMailClient struct{}
|
|
|
|
type Mailer interface {
|
|
SendCode(to string, code string) error
|
|
}
|
|
|
|
func (m MailClient) getMessage() (*mail.Msg, error) {
|
|
message := mail.NewMsg()
|
|
if err := message.From("auth@johncosta.tech"); err != nil {
|
|
return nil, err
|
|
}
|
|
|
|
return message, nil
|
|
}
|
|
|
|
func (m MailClient) SendCode(to string, code string) error {
|
|
msg, err := m.getMessage()
|
|
if err != nil {
|
|
return err
|
|
}
|
|
|
|
if err := msg.To(to); err != nil {
|
|
return err
|
|
}
|
|
|
|
msg.Subject("Login to Haystack")
|
|
msg.SetBodyString(mail.TypeTextPlain, code)
|
|
|
|
return m.client.DialAndSend(msg)
|
|
}
|
|
|
|
func (m TestMailClient) SendCode(to string, code string) error {
|
|
fmt.Printf("Email: %s | Code %s\n", to, code)
|
|
|
|
return nil
|
|
}
|
|
|
|
func CreateMailClient() (Mailer, error) {
|
|
mode := os.Getenv("MODE")
|
|
if mode == "DEV" {
|
|
return TestMailClient{}, nil
|
|
}
|
|
|
|
client, err := mail.NewClient(
|
|
"smtp.mailbox.org",
|
|
mail.WithSMTPAuth(mail.SMTPAuthPlain),
|
|
mail.WithUsername(os.Getenv("EMAIL_USERNAME")),
|
|
mail.WithPassword(os.Getenv("EMAIL_PASSWORD")),
|
|
)
|
|
|
|
if err != nil {
|
|
return MailClient{}, err
|
|
}
|
|
|
|
return MailClient{
|
|
client: client,
|
|
}, nil
|
|
}
|