-
Notifications
You must be signed in to change notification settings - Fork 0
/
gmailservice.go
163 lines (139 loc) · 3.93 KB
/
gmailservice.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
package mail
import (
"context"
"encoding/base64"
"encoding/json"
"fmt"
"log"
"net/http"
"os"
"path"
"golang.org/x/oauth2"
"golang.org/x/oauth2/google"
"google.golang.org/api/gmail/v1"
"google.golang.org/api/option"
)
type GmailService struct {
credentialsPath string
}
const (
CredentialsFileName = "client_secret.json"
TokenFileName = "request.token"
)
var GMailDomainNames = []string{"googlemail.com", "gmail.com"}
func NewGmailService(credentialsPath string) *GmailService {
return &GmailService{
credentialsPath: credentialsPath,
}
}
func (service *GmailService) GetAllUnreadMail(context context.Context) ([]Mail, error) {
result := make([]Mail, 0)
gmailService, err := service.getGmailService(context, gmail.GmailModifyScope)
if err != nil {
return result, err
}
user := "me"
listCall := gmailService.Users.Messages.List(user).Q("is:unread")
resp, err := listCall.Do()
if err != nil {
return result, fmt.Errorf("unable to retrieve messages: %v", err)
}
for _, message := range resp.Messages {
fullMessage, err := gmailService.Users.Messages.Get(user, message.Id).Format("full").Do()
if err != nil {
return result, err
}
subject := extractSubject(fullMessage.Payload.Headers)
body := extractPlainTextBody(fullMessage.Payload.Parts)
result = append(result, Mail{
Id: message.Id,
Subject: subject,
Body: body,
})
}
return result, nil
}
func (service *GmailService) MarkMailAsRead(context context.Context, mail Mail) error {
gmailService, err := service.getGmailService(context, gmail.GmailModifyScope)
if err != nil {
return err
}
req := &gmail.ModifyMessageRequest{
RemoveLabelIds: []string{"UNREAD"},
}
_, err = gmailService.Users.Messages.Modify("me", mail.Id, req).Do()
if err != nil {
return err
}
return nil
}
func extractSubject(headers []*gmail.MessagePartHeader) string {
for _, header := range headers {
if header.Name == "Subject" {
return header.Value
}
}
return ""
}
func extractPlainTextBody(parts []*gmail.MessagePart) string {
for _, part := range parts {
if part.MimeType == "text/plain" {
data, err := base64.URLEncoding.DecodeString(part.Body.Data)
if err != nil {
log.Printf("Error decoding body data: %v", err)
continue
}
return string(data)
}
// Handle multipart email: recursively check for plain text
if len(part.Parts) > 0 {
body := extractPlainTextBody(part.Parts)
if body != "" {
return body
}
}
}
return ""
}
func (service *GmailService) getGmailService(context context.Context, scope ...string) (*gmail.Service, error) {
config, err := GetGmailConfig(service.credentialsPath, scope...)
if err != nil {
return nil, err
}
client, err := service.getClient(context, config)
if err != nil {
return nil, err
}
return gmail.NewService(context, option.WithHTTPClient(client))
}
func GetGmailConfig(credentialsPath string, scope ...string) (*oauth2.Config, error) {
b, err := os.ReadFile(path.Join(credentialsPath, CredentialsFileName))
if err != nil {
return nil, err
}
// If modifying these scopes, delete your previously saved token.json.
return google.ConfigFromJSON(b, scope...)
}
// Retrieve a token, saves the token, then returns the generated client.
func (service *GmailService) getClient(context context.Context, config *oauth2.Config) (*http.Client, error) {
// The file token.json stores the user's access and refresh tokens, and is
// created automatically when the authorization flow completes for the first
// time.
tokenFilePath := path.Join(service.credentialsPath, TokenFileName)
token, err := tokenFromFile(tokenFilePath)
if err != nil {
return nil, err
}
return config.Client(context, token), nil
}
// Retrieves a token from a local file.
func tokenFromFile(filePath string) (*oauth2.Token, error) {
file, err := os.Open(filePath)
if err != nil {
return nil, err
}
defer file.Close()
token := &oauth2.Token{}
err = json.NewDecoder(file).Decode(token)
return token, err
}