package clients import ( "bytes" "encoding/json" "fmt" "github.com/gofiber/fiber/v2" "mime/multipart" ) type Deps struct { SmtpApiUrl string SmtpHost string SmtpPort string SmtpSender string ApiKey string FiberClient *fiber.Client } type SmtpClient struct { smtpApiUrl string smtpHost string smtpPort 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, smtpHost: deps.SmtpHost, smtpPort: deps.SmtpPort, 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"` } 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 }