-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy pathsend.go
86 lines (73 loc) · 1.96 KB
/
send.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
package azmail
import (
"bytes"
"encoding/json"
"errors"
"net/http"
)
type mailMessage struct {
Attachments []MailAttachment `json:"attachments,omitempty"`
Content MailContent `json:"content"`
Recipients MailRecipients `json:"recipients"`
ReplyTo []MailAddress `json:"replyTo,omitempty"`
SenderAddr string `json:"senderAddress"`
UserEngagementTrackingDisabled bool `json:"userEngagementTrackingDisabled"`
}
func (c *Client) newMailMessage(mail Mail) mailMessage {
return mailMessage{
mail.Attachments,
mail.Content,
mail.Recipients,
nil,
c.senderAddr,
true,
}
}
// SendMails sends multiple mails. If any errors are encountered, the error is saved and later returned.
// Encountering errors does not stop later emails from being sent.
func (c *Client) SendMails(mails ...*Mail) error {
var errs []error
for _, mail := range mails {
msg := c.newMailMessage(*mail)
if err := c.sendMessage(msg); err != nil {
errs = append(errs, err)
}
}
return errors.Join(errs...)
}
type errorResponse struct {
Error struct {
AdditionalInfo []struct {
Info any `json:"info"`
Type string `json:"type"`
} `json:"additionalInfo"`
Code string `json:"code"`
Details []errorResponse `json:"details"`
Message string `json:"message"`
Target string `json:"target"`
} `json:"error"`
}
func (c *Client) sendMessage(msg mailMessage) error {
req, err := c.generateSignedMessageRequest(msg)
if err != nil {
return err
}
resp, err := http.DefaultClient.Do(req)
if err != nil {
return err
}
if resp.StatusCode == http.StatusAccepted {
return nil
}
var (
b bytes.Buffer
errResp errorResponse
)
if _, err = b.ReadFrom(resp.Body); err != nil {
return err
}
if err = json.Unmarshal(b.Bytes(), &errResp); err != nil {
return err
}
return errors.New(errResp.Error.Message)
}