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"
|
|
|
|
)
|
|
|
|
|
2021-04-30 16:14:29 +03:00
|
|
|
type MailWhaleSendingService struct {
|
2021-04-12 23:57:52 +03:00
|
|
|
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"`
|
|
|
|
}
|
|
|
|
|
2021-04-30 16:14:29 +03:00
|
|
|
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,
|
|
|
|
},
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2021-04-30 16:14:29 +03:00
|
|
|
func (s *MailWhaleSendingService) Send(mail *models.Mail) error {
|
|
|
|
if len(mail.To) == 0 {
|
2021-04-10 11:48:06 +03:00
|
|
|
return errors.New("not sending mail as recipient mail address seems to be invalid")
|
2021-04-05 17:25:13 +03:00
|
|
|
}
|
|
|
|
|
|
|
|
sendRequest := &MailWhaleSendRequest{
|
2021-04-30 16:14:29 +03:00
|
|
|
To: mail.To.Strings(),
|
|
|
|
Subject: mail.Subject,
|
2021-04-05 17:25:13 +03:00
|
|
|
}
|
2021-04-30 16:14:29 +03:00
|
|
|
if mail.Type == models.HtmlType {
|
|
|
|
sendRequest.Html = mail.Body
|
2021-04-05 17:25:13 +03:00
|
|
|
} else {
|
2021-04-30 16:14:29 +03:00
|
|
|
sendRequest.Text = mail.Body
|
2021-04-05 17:25:13 +03:00
|
|
|
}
|
|
|
|
payload, _ := json.Marshal(sendRequest)
|
|
|
|
|
2021-04-10 01:07:13 +03:00
|
|
|
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
|
|
|
|
}
|
|
|
|
|
2021-04-10 01:07:13 +03:00
|
|
|
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
|
|
|
|
}
|