-
Notifications
You must be signed in to change notification settings - Fork 4
/
email.go
71 lines (62 loc) · 1.61 KB
/
email.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
package main
import (
"bytes"
"encoding/json"
"fmt"
"net/http"
"strings"
"time"
)
func sendEmail(url string, e EmailRequest) error {
c := &http.Client{
Timeout: 15 * time.Second,
}
var jsonData []byte
var err error
if strings.Contains(url, "sendgrid") {
sendGridReq := NewSingleEmailPlainText(
NewEmail(opts.EmailFromName, opts.EmailFrom),
e.Subject,
NewEmail("", e.MailTo),
e.TextMessage)
jsonData, err = json.Marshal(sendGridReq)
} else {
jsonData, err = json.Marshal(e)
}
if err != nil {
return err
}
req, err := http.NewRequest("POST", url, bytes.NewBuffer(jsonData))
if err != nil {
return err
}
req.Header.Add("Authorization", "Bearer "+opts.EmailToken)
req.Header.Set("Content-Type", "application/json")
resp, err := c.Do(req)
if err != nil {
return err
}
defer resp.Body.Close()
if resp.StatusCode != http.StatusOK && resp.StatusCode != http.StatusAccepted {
return fmt.Errorf("could not send email: %v %v", resp.Status, resp.StatusCode)
}
return nil
}
func prepareEmail(mailTo string, data map[string]interface{}, templateSubject string, defaultSubject string,
templateText string, defaultText string, templateHtml string, lang string) EmailRequest {
subject := parseTemplate(templateSubject+lang+".tmpl", data)
if subject == "" {
subject = defaultSubject
}
textMessage := parseTemplate(templateText+lang+".tmpl", data)
if textMessage == "" {
textMessage = defaultText
}
htmlMessage := parseTemplate(templateHtml+lang+".tmpl", data)
return EmailRequest{
MailTo: mailTo,
Subject: subject,
TextMessage: textMessage,
HtmlMessage: htmlMessage,
}
}