forked from reAsOn2010/go-sendcloud
-
Notifications
You must be signed in to change notification settings - Fork 0
/
send.go
90 lines (82 loc) · 1.92 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
87
88
89
90
package sendcloud
import (
"encoding/json"
"fmt"
"net/url"
"regexp"
"strings"
)
type Mail interface {
From() string // mail-from address
To() []string
Cc() []string
Bcc() []string
ReplyTo() string // reply-to address
Subject() string
Html() string // HTML mail body
Text() string // plain text mail body
Headers() map[string]string // extra mail headers
}
var EMAIL_DOMAIN_RE = regexp.MustCompile(`[^<>]+<?.+@([^<>]+)>?`)
func (c *Client) Send(m Mail) (id string, err error) {
// extract the sending domain
match := EMAIL_DOMAIN_RE.FindStringSubmatch(m.From())
if len(match) != 2 {
err = fmt.Errorf("invalid From address: %s", m.From())
return
}
domain := match[1]
d := url.Values{}
d.Add("resp_email_id", "true")
d.Add("from", m.From())
if to := m.To(); len(to) > 0 {
d.Add("to", strings.Join(to, ";"))
}
if cc := m.Cc(); len(cc) > 0 {
d.Add("cc", strings.Join(cc, ";"))
}
if bcc := m.Bcc(); len(bcc) > 0 {
d.Add("bcc", strings.Join(bcc, ";"))
}
if replyto := m.ReplyTo(); replyto != "" {
d.Add("replyto", replyto)
}
d.Add("subject", m.Subject())
if m.Html() != "" {
d.Add("html", m.Html())
} else {
d.Add("html", m.Text())
}
headers := m.Headers()
if headers != nil {
hb, err := json.Marshal(headers)
if err != nil {
return "", err
}
d.Add("headers", string(hb))
}
body, err := c.do("mail.send", domain, d)
if err != nil {
return
}
var reply struct {
Msg string `json:"message"`
Errs []string `json:"errors"`
Ids []string `json:"email_id_list"`
}
json.Unmarshal(body, &reply)
if reply.Msg != "success" {
if len(reply.Errs) > 0 {
//err = fmt.Errorf("SendCloud error: %s", reply.Errs[0])
err = c.logger.ErrorLog("sendcloud.error", 0, reply.Errs[0])
} else {
//err = fmt.Errorf("SendCloud error: unknown")
err = c.logger.ErrorLog("sendcloud.error", 0, "unknown")
}
return
}
if len(reply.Ids) > 0 {
id = reply.Ids[0]
}
return
}