92 lines
1.7 KiB
Go
92 lines
1.7 KiB
Go
|
package clients
|
||
|
|
||
|
import (
|
||
|
"bytes"
|
||
|
"fmt"
|
||
|
"github.com/gofiber/fiber/v2"
|
||
|
"mime/multipart"
|
||
|
)
|
||
|
|
||
|
type Deps struct {
|
||
|
SmtpApiUrl string
|
||
|
SmtpHost string
|
||
|
SmtpPort string
|
||
|
SmtpSender string
|
||
|
Username string
|
||
|
Password string
|
||
|
ApiKey string
|
||
|
FiberClient *fiber.Client
|
||
|
}
|
||
|
|
||
|
type SmtpClient struct {
|
||
|
smtpApiUrl string
|
||
|
smtpHost string
|
||
|
smtpPort string
|
||
|
smtpSender string
|
||
|
username string
|
||
|
password string
|
||
|
apiKey string
|
||
|
fiberClient *fiber.Client
|
||
|
}
|
||
|
|
||
|
func NewSmtpClient(deps Deps) *SmtpClient {
|
||
|
if deps.FiberClient == nil {
|
||
|
deps.FiberClient = fiber.AcquireClient()
|
||
|
}
|
||
|
return &SmtpClient{
|
||
|
smtpApiUrl: deps.SmtpApiUrl,
|
||
|
smtpHost: deps.SmtpHost,
|
||
|
smtpPort: deps.SmtpPort,
|
||
|
smtpSender: deps.SmtpSender,
|
||
|
username: deps.Username,
|
||
|
password: deps.Password,
|
||
|
apiKey: deps.ApiKey,
|
||
|
fiberClient: deps.FiberClient,
|
||
|
}
|
||
|
}
|
||
|
|
||
|
type Message struct {
|
||
|
To string
|
||
|
Subject string
|
||
|
HtmlBody string
|
||
|
}
|
||
|
|
||
|
func (m *SmtpClient) MailSender(data Message) error {
|
||
|
form := new(bytes.Buffer)
|
||
|
writer := multipart.NewWriter(form)
|
||
|
|
||
|
fields := map[string]string{
|
||
|
"from": m.smtpSender,
|
||
|
"to": data.To,
|
||
|
"subject": data.Subject,
|
||
|
"html": data.HtmlBody,
|
||
|
}
|
||
|
|
||
|
for key, value := range fields {
|
||
|
if err := writer.WriteField(key, value); err != nil {
|
||
|
return err
|
||
|
}
|
||
|
}
|
||
|
|
||
|
if err := writer.Close(); err != nil {
|
||
|
return err
|
||
|
}
|
||
|
|
||
|
req := m.fiberClient.Post(m.smtpApiUrl).Body(form.Bytes()).ContentType(writer.FormDataContentType())
|
||
|
if m.apiKey != "" {
|
||
|
req.Set("Authorization", m.apiKey)
|
||
|
}
|
||
|
|
||
|
statusCode, body, errs := req.Bytes()
|
||
|
if errs != nil {
|
||
|
return errs[0]
|
||
|
}
|
||
|
|
||
|
if statusCode != fiber.StatusOK {
|
||
|
err := fmt.Errorf("the SMTP service returned an error: %d Response body: %s", statusCode, body)
|
||
|
return err
|
||
|
}
|
||
|
|
||
|
return nil
|
||
|
}
|