-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathmain.go
222 lines (177 loc) · 4.93 KB
/
main.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
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
package main
import (
"bufio"
"context"
"encoding/json"
"fmt"
"github.com/BrianLeishman/go-imap"
"github.com/google/generative-ai-go/genai"
"google.golang.org/api/option"
"io/ioutil"
"log"
"os"
"reflect"
"strings"
"time"
)
const (
apiKey = "API_KEY"
imapServer = "MAIL_SERVER"
imapPort = 993
inboxFolder = "INBOX"
shortAlias = "SHORT_ALIAS"
)
const requestDelay = 3 * time.Second
var categories = []string{"INBOX", "INBOX.Spam"}
var categoriesString = strings.Join(categories, ", ")
type Credentials struct {
Login string `json:"login"`
Password string `json:"password"`
}
func getCredentials() (string, string) {
var creds Credentials
credsFile := "credentials.json"
reader := bufio.NewReader(os.Stdin)
if _, err := os.Stat(credsFile); err == nil {
data, err := ioutil.ReadFile(credsFile)
if err == nil {
err := json.Unmarshal(data, &creds)
if err == nil {
fmt.Printf("Use saved account: %s? (y/n): ", creds.Login)
choice, _ := reader.ReadString('\n')
choice = strings.TrimSpace(choice)
if choice == "y" {
return creds.Login, creds.Password
}
}
}
}
fmt.Print("Enter login (without " + shortAlias + ", e.g., 'dev'): ")
login, _ := reader.ReadString('\n')
login = strings.TrimSpace(login)
if !strings.Contains(login, "@") {
login += shortAlias
}
fmt.Print("Enter password: ")
bytePassword, _ := reader.ReadString('\n')
password := strings.TrimSpace(bytePassword)
creds.Login = login
creds.Password = password
data, _ := json.Marshal(creds)
err := ioutil.WriteFile(credsFile, data, 0644)
check(err)
return login, password
}
func classifyEmail(emailSubject string, emailSender string, emailContent string) (string, error) {
ctx := context.Background()
client, err := genai.NewClient(ctx, option.WithAPIKey(apiKey))
if err != nil {
return "", err
}
defer client.Close()
model := client.GenerativeModel("gemini-1.5-flash")
resp, err := model.GenerateContent(ctx, genai.Text("Here is the subject of the letter, your task is to answer me in one word the type of this letter. Available categories are: "+categoriesString+". Mail sender is: "+emailSender+". The email subject is: "+emailSubject+". The email content is: "+emailContent))
if err != nil {
return "", err
}
printResponse(resp)
if len(resp.Candidates) > 0 && len(resp.Candidates[0].Content.Parts) > 0 {
return fmt.Sprintf("%+v", resp.Candidates[0].Content.Parts[0]), nil
}
return "Other", nil
}
func printResponse(resp *genai.GenerateContentResponse) {
fmt.Printf("Response from Gemini: %+v\n", resp)
for _, cand := range resp.Candidates {
if cand.Content != nil {
for _, part := range cand.Content.Parts {
printStruct(part)
}
}
}
fmt.Println("---")
}
func printStruct(s interface{}) {
v := reflect.ValueOf(s)
t := reflect.TypeOf(s)
if v.Kind() == reflect.String {
fmt.Printf("String: %s\n", v.String())
return
}
fmt.Println("Type:", t)
for i := 0; i < v.NumField(); i++ {
field := v.Field(i)
fieldName := t.Field(i).Name
fmt.Printf("%s: %v\n", fieldName, field.Interface())
}
}
func mapCategoryToFolder(category string) string {
category = strings.TrimSpace(strings.ToLower(category))
for _, cat := range categories {
if strings.ToLower(strings.TrimSpace(cat)) == category {
return cat
}
}
return "INBOX"
}
func main() {
imap.Verbose = false
imap.RetryCount = 3
login, password := getCredentials()
log.Println("Connecting to IMAP...")
im, err := imap.New(login, password, imapServer, imapPort)
check(err)
defer im.Close()
log.Println("Login successful. Starting email processing...")
log.Println("Getting folders...")
folders, err := im.GetFolders()
check(err)
for _, folder := range folders {
log.Println("Folder: ", folder)
}
err = im.SelectFolder(inboxFolder)
check(err)
uids, err := im.GetUIDs("ALL")
check(err)
if len(uids) == 0 {
log.Println("No new emails.")
return
}
const batchSize = 50
totalMessages := len(uids)
for start := 1; start <= totalMessages; start += batchSize {
end := start + batchSize - 1
if end > totalMessages {
end = totalMessages
}
emails, err := im.GetEmails(uids...)
check(err)
for _, email := range emails {
time.Sleep(requestDelay)
log.Println("Processing email:", email.Subject)
var senders []string
for _, addr := range email.From {
senders = append(senders, addr)
}
emailSenders := strings.Join(senders, ",")
log.Println("Classifying email... Subject:", email.Subject, "Senders:", emailSenders)
category, err := classifyEmail(email.Subject, emailSenders, email.HTML)
check(err)
log.Println("Email classified as:", category)
folder := mapCategoryToFolder(category)
if folder != "INBOX" {
err = im.MoveEmail(email.UID, folder)
check(err)
log.Println("Email moved to folder:", folder)
} else {
log.Println("Email not moved to folder:", folder)
}
}
}
log.Println("All emails processed.")
}
func check(err error) {
if err != nil {
panic(err)
}
}