-
Notifications
You must be signed in to change notification settings - Fork 0
/
send.go
138 lines (121 loc) · 2.22 KB
/
send.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
package main
import (
"crypto/tls"
"errors"
"fmt"
"io/fs"
"net/smtp"
"os"
"path/filepath"
"github.com/gonejack/email"
"github.com/sirupsen/logrus"
)
type config struct {
From string
To string
Host string
Port int
Username string
Password string
}
type sender struct {
config
auth smtp.Auth
client *smtp.Client
}
func (s *sender) sendAndMove(emails []string) {
client, err := s.getClient()
if err != nil {
logrus.WithError(err).Fatalf("get client failed")
return
}
s.client = client
defer func() {
_ = s.client.Quit()
_ = s.client.Close()
}()
for _, eml := range emails {
log := logrus.WithField("email", eml)
log.Infof("sending")
err := s.sendEmail(eml)
if err != nil {
log.WithError(err).Errorf("send failed")
continue
}
log.Debugf("sent")
rename := filepath.Join(sentDir, filepath.Base(eml))
index := 1
for {
if _, err := os.Open(rename); errors.Is(err, fs.ErrNotExist) {
break
}
rename = fmt.Sprintf("%s#%d", rename, index)
index += 1
}
err = os.Rename(eml, rename)
if err != nil {
log.WithError(err).Errorf("move failed")
}
}
}
func (s *sender) sendEmail(eml string) (err error) {
file, err := os.Open(eml)
if err != nil {
return
}
defer file.Close()
e, err := email.NewEmailFromReader(file)
if err != nil {
return
}
e.From = s.getFrom()
e.To = []string{s.getTo()}
return e.SendWithClient(s.client)
}
func (s *sender) getClient() (c *smtp.Client, err error) {
addr := fmt.Sprintf("%s:%d", s.Host, s.Port)
auth := s.getAuth()
c, err = smtp.Dial(addr)
if err != nil {
return
}
err = c.Hello("localhost")
if err != nil {
return
}
ok, _ := c.Extension("STARTTLS")
if ok {
err = c.StartTLS(&tls.Config{ServerName: s.Host})
if err != nil {
return
}
}
if auth != nil {
ok, _ := c.Extension("AUTH")
if ok {
err = c.Auth(auth)
if err != nil {
return
}
}
}
return
}
func (s *sender) getFrom() string {
if *argFrom != "" {
return *argFrom
}
return s.From
}
func (s *sender) getTo() string {
if *argTo != "" {
return *argTo
}
return s.To
}
func (s *sender) getAuth() smtp.Auth {
if s.auth == nil {
s.auth = smtp.PlainAuth("", send.Username, send.Password, send.Host)
}
return s.auth
}