-
Notifications
You must be signed in to change notification settings - Fork 3
/
Copy pathgmail.go
183 lines (149 loc) · 4.26 KB
/
gmail.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
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
package email
import (
"bytes"
"context"
"encoding/base64"
"fmt"
"io/ioutil"
"net/http"
"path"
"strings"
"text/template"
"golang.org/x/oauth2"
"golang.org/x/oauth2/google"
"google.golang.org/api/gmail/v1"
gooleoauth2 "google.golang.org/api/oauth2/v2"
option "google.golang.org/api/option"
myoauth2 "github.com/opensourceways/app-cla-server/oauth2"
"github.com/opensourceways/app-cla-server/util"
)
func init() {
EmailAgent.emailClients["gmail"] = &gmailClient{}
}
type gmailClient struct {
cfg *oauth2.Config
emailTemp *template.Template
}
func (this *gmailClient) initialize(path string) error {
cfg, err := this.getOauth2Config(path)
if err != nil {
return fmt.Errorf("Failtd to initialize gmail client: %s", err.Error())
}
str := emailTempWithAttachmentForGmail()
tmpl, err := template.New("email").Parse(str)
if err != nil {
return fmt.Errorf("Failtd to initialize gmail client: %s", err.Error())
}
this.emailTemp = tmpl
this.cfg = cfg
return nil
}
func (this *gmailClient) GetToken(code, scope string) (*oauth2.Token, error) {
if this.cfg == nil {
return nil, fmt.Errorf("gmail has not been initialized")
}
return myoauth2.FetchOauth2Token(this.cfg, code)
}
func (this *gmailClient) GetAuthorizedEmail(token *oauth2.Token) (string, error) {
ctx := context.Background()
srv, err := gooleoauth2.NewService(
ctx, option.WithTokenSource(this.cfg.TokenSource(ctx, token)))
if err != nil {
return "", err
}
info, err := srv.Userinfo.V2.Me.Get().Do()
if err != nil {
return "", err
}
return info.Email, nil
}
func (this *gmailClient) GetOauth2CodeURL(state string) string {
return myoauth2.GetOauth2CodeURL(this.cfg, state)
}
func (this *gmailClient) SendEmail(token *oauth2.Token, msg *EmailMessage) error {
client := this.cfg.Client(context.Background(), token)
srv, err := gmail.New(client)
if err != nil {
return err
}
msg1, err := this.createGmailMessage(msg)
if err != nil {
return err
}
_, err = srv.Users.Messages.Send("me", msg1).Do()
return err
}
func (this *gmailClient) getOauth2Config(path string) (*oauth2.Config, error) {
b, err := ioutil.ReadFile(path)
if err != nil {
return nil, fmt.Errorf("Unable to read client secret file: %v", err)
}
config, err := google.ConfigFromJSON(b, this.getScope()...)
if err != nil {
return nil, fmt.Errorf("Unable to parse client secret file to config: %v", err)
}
return config, nil
}
func (this *gmailClient) getScope() []string {
return []string{gooleoauth2.UserinfoEmailScope, gmail.GmailSendScope}
}
func (this *gmailClient) createGmailMessage(msg *EmailMessage) (*gmail.Message, error) {
attachment := msg.Attachment
if attachment == "" {
return simpleGmailMessage(msg), nil
}
fileBytes, err := ioutil.ReadFile(attachment)
if err != nil {
return nil, fmt.Errorf("Unable to read file for attachment: %s", err.Error())
}
data := struct {
To string
Subject string
Content string
Boundary string
FileName string
FileData string
FileMIMEType string
}{
To: msg.To[0],
Subject: msg.Subject,
Content: msg.Content,
Boundary: util.RandStr(32, "alphanum"),
FileData: base64.StdEncoding.EncodeToString(fileBytes),
FileName: path.Base(attachment),
FileMIMEType: http.DetectContentType(fileBytes),
}
buf := new(bytes.Buffer)
err = this.emailTemp.Execute(buf, data)
if err != nil {
return nil, fmt.Errorf("parse template failed: %s", err.Error())
}
return &gmail.Message{
Raw: base64.URLEncoding.EncodeToString(buf.Bytes()),
}, nil
}
func simpleGmailMessage(msg *EmailMessage) *gmail.Message {
to := strings.Join(msg.To, "; ")
raw := fmt.Sprintf("To: %s\r\nSubject: %s\r\n\r\n%s", to, msg.Subject, msg.Content)
return &gmail.Message{
Raw: base64.URLEncoding.EncodeToString([]byte(raw)),
}
}
func emailTempWithAttachmentForGmail() string {
return `Content-Type: multipart/mixed; boundary={{.Boundary}}
MIME-Version: 1.0
to: {{.To}}
subject: {{.Subject}}
--{{.Boundary}}
Content-Type: text/plain; charset="UTF-8"
MIME-Version: 1.0
Content-Transfer-Encoding: 7bit
{{.Content}}
--{{.Boundary}}
Content-Type: {{.FileMIMEType}}; name="{{.FileName}}"
MIME-Version: 1.0
Content-Transfer-Encoding: base64
Content-Disposition: attachment; filename="{{.FileName}}"
{{.FileData}}
--{{.Boundary}}--`
}