122 lines
2.5 KiB
Go
122 lines
2.5 KiB
Go
package client
|
|
|
|
import (
|
|
"bytes"
|
|
"encoding/json"
|
|
"fmt"
|
|
"github.com/gofiber/fiber/v2"
|
|
"mime/multipart"
|
|
"penahub.gitlab.yandexcloud.net/pena-services/email-tester/model"
|
|
)
|
|
|
|
type Deps struct {
|
|
SmtpApiUrl string
|
|
SmtpSender string
|
|
ApiKey string
|
|
FiberClient *fiber.Client
|
|
}
|
|
|
|
type SmtpClient struct {
|
|
smtpApiUrl string
|
|
smtpSender string
|
|
apiKey string
|
|
fiberClient *fiber.Client
|
|
}
|
|
|
|
func NewSmtpClient(deps Deps) *SmtpClient {
|
|
if deps.FiberClient == nil {
|
|
deps.FiberClient = fiber.AcquireClient()
|
|
}
|
|
return &SmtpClient{
|
|
smtpApiUrl: deps.SmtpApiUrl,
|
|
smtpSender: deps.SmtpSender,
|
|
apiKey: deps.ApiKey,
|
|
fiberClient: deps.FiberClient,
|
|
}
|
|
}
|
|
|
|
type Message struct {
|
|
To string
|
|
Subject string
|
|
HtmlBody string
|
|
Attachments []Attachment
|
|
}
|
|
|
|
type Attachment struct {
|
|
Name string `json:"name"`
|
|
// data в base64 это файл
|
|
Data string `json:"body"`
|
|
}
|
|
|
|
type TemplateData struct {
|
|
QuizConfig model.ResultInfo
|
|
AnswerContent model.ResultContent
|
|
AllAnswers []model.ResultAnswer
|
|
QuestionsMap map[uint64]string
|
|
AnswerTime 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,
|
|
}
|
|
|
|
if data.Attachments != nil && len(data.Attachments) > 0 {
|
|
attachmentJson, err := json.Marshal(data.Attachments)
|
|
if err != nil {
|
|
return err
|
|
}
|
|
fields["files"] = string(attachmentJson)
|
|
}
|
|
|
|
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
|
|
}
|
|
|
|
func (m *SmtpClient) SendMailWithAttachment(recipient, subject string, emailTemplate string, data TemplateData, attachments []Attachment) error {
|
|
sanitizedData := sanitizeHTMLData(data)
|
|
text, err := generateTextFromTemplate(sanitizedData, emailTemplate)
|
|
if err != nil {
|
|
return err
|
|
}
|
|
|
|
msg := Message{
|
|
To: recipient,
|
|
Subject: subject,
|
|
HtmlBody: text,
|
|
Attachments: attachments,
|
|
}
|
|
|
|
return m.MailSender(msg)
|
|
}
|