-
Notifications
You must be signed in to change notification settings - Fork 0
/
sendgrid.go
90 lines (80 loc) · 1.89 KB
/
sendgrid.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 pmail
import (
"encoding/base64"
"errors"
"net/mail"
"strings"
sgmail "github.com/sendgrid/sendgrid-go/helpers/mail"
)
// AsSGMailV3 returns a sendgrid SGMailV3 object for this email
func (m *Mail) AsSGMailV3() *sgmail.SGMailV3 {
pers := &sgmail.Personalization{
To: makeSGEmails(m.To),
From: makeSGEmail(m.From),
CC: makeSGEmails(m.Cc),
BCC: makeSGEmails(m.Bcc),
}
// From ReplyTo[] To[] Cc[] Bcc[] Body MessageId
res := &sgmail.SGMailV3{
From: makeSGEmail(m.From),
Subject: m.Body.Headers.Get("Subject"),
Personalizations: []*sgmail.Personalization{pers},
}
// res.Content && res.Attachments
scanSGPart(res, m.Body)
return res
}
func scanSGPart(res *sgmail.SGMailV3, part *Part) error {
if strings.HasPrefix(part.Type, "text/") {
data, err := part.readBody()
if err != nil {
return err
}
res.AddContent(sgmail.NewContent(part.Type, string(data)))
return nil
} else if part.IsContainer() {
for _, sub := range part.Children {
scanSGPart(res, sub)
}
return nil
} else if part.Data != nil || part.GetBody != nil {
// attachment
data, err := part.readBody()
if err != nil {
return err
}
attach := &sgmail.Attachment{
Content: base64.StdEncoding.EncodeToString(data),
Type: part.Type,
// TODO Filename, etc
}
res.AddAttachment(attach)
return nil
}
return errors.New("unsupported mime type")
}
func makeSGEmail(addr *mail.Address) *sgmail.Email {
return &sgmail.Email{
Name: addr.Name,
Address: addr.Address,
}
}
func makeSGEmails(addrs []*mail.Address) []*sgmail.Email {
res := make([]*sgmail.Email, len(addrs))
for n, a := range addrs {
res[n] = makeSGEmail(a)
}
return res
}
func convertSGHeaders(h Header) map[string]string {
res := make(map[string]string)
for k, v := range h {
switch k {
case "Subject", "Content-Type":
// do nothing
default:
res[k] = v[0]
}
}
return res
}