1
0
mirror of https://github.com/muety/wakapi.git synced 2023-08-10 21:12:56 +03:00
wakapi/services/mail/mailwhale.go

69 lines
1.6 KiB
Go
Raw Normal View History

2021-04-05 17:25:13 +03:00
package mail
import (
"bytes"
"encoding/json"
"errors"
"fmt"
conf "github.com/muety/wakapi/config"
"github.com/muety/wakapi/models"
2023-07-09 21:16:34 +03:00
"github.com/muety/wakapi/utils"
2021-04-05 17:25:13 +03:00
"net/http"
"time"
)
type MailWhaleSendingService struct {
config conf.MailwhaleMailConfig
2021-04-05 17:25:13 +03:00
httpClient *http.Client
}
type MailWhaleSendRequest struct {
To []string `json:"to"`
Subject string `json:"subject"`
Text string `json:"text"`
Html string `json:"html"`
TemplateId string `json:"template_id"`
TemplateVars map[string]string `json:"template_vars"`
}
func NewMailWhaleSendingService(config conf.MailwhaleMailConfig) *MailWhaleSendingService {
return &MailWhaleSendingService{
config: config,
2021-04-05 17:25:13 +03:00
httpClient: &http.Client{
Timeout: 10 * time.Second,
},
}
}
func (s *MailWhaleSendingService) Send(mail *models.Mail) error {
if len(mail.To) == 0 {
return errors.New("not sending mail as recipient mail address seems to be invalid")
2021-04-05 17:25:13 +03:00
}
sendRequest := &MailWhaleSendRequest{
To: mail.To.Strings(),
Subject: mail.Subject,
2021-04-05 17:25:13 +03:00
}
if mail.Type == models.HtmlType {
sendRequest.Html = mail.Body
2021-04-05 17:25:13 +03:00
} else {
sendRequest.Text = mail.Body
2021-04-05 17:25:13 +03:00
}
payload, _ := json.Marshal(sendRequest)
req, err := http.NewRequest(http.MethodPost, fmt.Sprintf("%s/api/mail", s.config.Url), bytes.NewBuffer(payload))
2021-04-05 17:25:13 +03:00
if err != nil {
return err
}
req.SetBasicAuth(s.config.ClientId, s.config.ClientSecret)
2021-04-05 17:25:13 +03:00
req.Header.Set("Content-Type", "application/json")
2023-07-09 21:16:34 +03:00
_, err = utils.RaiseForStatus(s.httpClient.Do(req))
2021-04-05 17:25:13 +03:00
if err != nil {
return err
}
return nil
}