-
Notifications
You must be signed in to change notification settings - Fork 0
/
go-ssmtp.go
383 lines (319 loc) · 10 KB
/
go-ssmtp.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
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
package main
import (
"bufio"
"bytes"
"crypto/tls"
"flag"
"fmt"
"github.com/blackjack/syslog"
"math/rand"
"net/mail"
"net/smtp"
"net/textproto"
"os"
"os/user"
"reflect"
"regexp"
"strconv"
"strings"
"time"
)
var config = &Configuration{
Verbose: false,
ConfigFile: "/etc/go-ssmtp.ini",
Port: 25,
Server: "127.0.0.1",
Postmaster: "postmaster",
ScanMessage: false,
Message_Subject: "(no subject)",
}
type Configuration struct {
Verbose bool
ConfigFile string
Hostname string
Server string
Port int
Postmaster string
ScanMessage bool
Authentication_User string
Authentication_Password string
Authentication_Identity string
Authentication_Mechanism string
Authentication_ForceStartTLS bool
Authentication_InsecureSkipVerify bool
Message_To []string
Message_From string
Message_FromName string
Message_Subject string
Message_FromCronDaemon bool
}
func generateMessageId() string {
const CHARS = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz"
bytes := make([]byte, 16)
for i, r := 0, rand.New(rand.NewSource(time.Now().UnixNano())); i < len(bytes); i++ {
bytes[i] = CHARS[r.Intn(len(CHARS))]
}
return string(bytes)
}
func (c *Configuration) ParseFile(file string) error {
var matchSection = regexp.MustCompile(`^\[([^]]+)\]$`)
var matchPair = regexp.MustCompile(`^([^#;=]+)=(.*)$`)
f, err := os.Open(file)
if err != nil {
return err
}
defer f.Close()
s := bufio.NewScanner(f)
s.Split(bufio.ScanLines)
var n, section = 1, ""
for s.Scan() {
l := s.Text()
if 0 == len(l) || ';' == l[0] {
continue
} else if parts := matchSection.FindStringSubmatch(l); parts != nil {
section = parts[1]
} else if parts := matchPair.FindStringSubmatch(l); parts != nil {
k, v := parts[1], parts[2]
if section != "" {
k = section + "_" + k
}
if !c.Get(k).IsValid() {
fmt.Fprintf(os.Stderr, "Warning: unknown configuration variable %s, line %d\n", k, n)
} else if "string" == config.Get(k).Type().String() {
c.Get(k).SetString(v)
} else if "bool" == config.Get(k).Type().String() {
c.Get(k).SetBool("1" == v)
} else if "int" == config.Get(k).Type().String() {
if i, err := strconv.ParseInt(v, 10, 64); err != nil {
fmt.Fprintf(os.Stderr, "Warning: could not parse value `%s` for %s, line %d\n", v, k, n)
} else {
c.Get(k).SetInt(i)
}
} else {
fmt.Fprintf(os.Stderr, "Warning: unsupported type %v for %s\n", config.Get(k).Type(), k)
}
} else {
return fmt.Errorf("Failed to parse config, line %d: %s", n, l)
}
n++
}
return nil
}
func (c *Configuration) Get(k string) reflect.Value {
r := reflect.ValueOf(c)
return reflect.Indirect(r).FieldByName(k)
}
func compose() (*mail.Message, error) {
// Make sure we can re-use Stdin even after being consumed by mail.ReadMessage
b := bytes.Buffer{}
b.ReadFrom(os.Stdin)
msg := b.String()
m, err := mail.ReadMessage(bytes.NewBufferString(msg))
if err != nil {
if config.ScanMessage {
return nil, fmt.Errorf("ScanMessage: cannot parse message: %s", err)
}
// Assume there are no headers in the message
m = &mail.Message{
Header: mail.Header(textproto.MIMEHeader{}),
Body: bufio.NewReader(bytes.NewBufferString(msg)),
}
}
// Make sure all required fields are set
if 0 == len(m.Header["From"]) {
m.Header["From"] = []string{(&mail.Address{
Name: config.Message_FromName,
Address: config.Message_From,
}).String()}
} else if from, err := mail.ParseAddress(m.Header["From"][0]); config.ScanMessage && err == nil {
// Parse and put in config; to be used by c.Mail
config.Message_From = from.Address
}
if 0 == len(m.Header["To"]) {
m.Header["To"] = config.Message_To
}
if 0 == len(m.Header["Date"]) {
m.Header["Date"] = []string{time.Now().Format("Mon, 2 Jan 2006 15:04:05 -0700")}
}
if 0 == len(m.Header["Message-Id"]) {
m.Header["Message-Id"] = []string{"<GOSSMTP." + generateMessageId() + "@" + config.Hostname + ">"}
}
if 0 == len(m.Header["Subject"]) {
m.Header["Subject"] = []string{config.Message_Subject}
}
return m, nil
}
func connect() (*smtp.Client, error) {
c, err := smtp.Dial(fmt.Sprintf("%s:%d", config.Server, config.Port))
if err != nil {
return nil, fmt.Errorf("while connecting to %s on port %d: %s", config.Server, config.Port, err)
}
if err := c.Hello(config.Hostname); err != nil {
return nil, fmt.Errorf("while sending Hello `%s`: %s", config.Hostname, err)
}
if ok, _ := c.Extension("STARTTLS"); ok {
if err = c.StartTLS(&tls.Config{ServerName: config.Server, InsecureSkipVerify: config.Authentication_InsecureSkipVerify}); err != nil {
return nil, fmt.Errorf("while enabling StartTLS: %s", err)
}
} else if config.Authentication_ForceStartTLS {
return nil, fmt.Errorf("server does not support StartTLS")
}
switch config.Authentication_Mechanism {
case "CRAM-MD5":
auth := smtp.CRAMMD5Auth(
config.Authentication_User,
config.Authentication_Password,
)
if ok, _ := c.Extension("AUTH"); ok {
if err = c.Auth(auth); err != nil {
return nil, fmt.Errorf("while authenticating: %s", err)
} else if config.Verbose {
return nil, fmt.Errorf("Info: using authentication: CRAM-MD5")
}
}
case "PLAIN":
auth := smtp.PlainAuth(
config.Authentication_Identity,
config.Authentication_User,
config.Authentication_Password,
config.Server,
)
if ok, _ := c.Extension("AUTH"); ok {
if err = c.Auth(auth); err != nil {
return nil, fmt.Errorf("while authenticating: %s", err)
} else if config.Verbose {
fmt.Println("Info: using authentication: PLAIN")
}
}
default:
if config.Verbose {
fmt.Println("Info: not using authentication")
}
}
return c, nil
}
func send(c *smtp.Client, m *mail.Message) error {
if err := c.Mail(config.Message_From); err != nil {
return fmt.Errorf("while setting From `%s`: %s", config.Message_From, err)
}
if config.ScanMessage {
for _, i := range []string{"To", "Cc", "Bcc"} {
if 0 == len(m.Header[i]) {
continue
}
if l, err := m.Header.AddressList(i); err != nil {
fmt.Fprintf(os.Stderr, "ScanMessage: Could not parse recipients in %s `%s`; %s", i, l, err)
} else {
for _, v := range l {
config.Message_To = append(config.Message_To, v.Address)
}
}
}
if 0 == len(config.Message_To) {
fmt.Fprintln(os.Stderr, "ScanMessage: No recipients found in message-body")
}
}
for _, to := range config.Message_To {
if err := c.Rcpt(to); err != nil {
return fmt.Errorf("while setting Recipient `%s`: %s", to, err)
}
}
w, err := c.Data()
if err != nil {
return fmt.Errorf("while setting Data: %s", err)
}
var s = ""
for k, h := range m.Header {
for _, v := range h {
s += k + ": " + v + "\r\n"
}
}
b := bytes.Buffer{}
b.ReadFrom(m.Body)
if _, err := w.Write([]byte(s + "\r\n" + b.String())); err != nil {
return fmt.Errorf("while sending message: %s", err)
}
if err = w.Close(); err != nil {
return fmt.Errorf("while closing message: %s", err)
}
if err = c.Quit(); err != nil {
return fmt.Errorf("while closing connection: %s", err)
}
return nil
}
func init() {
if h, err := os.Hostname(); err == nil {
config.Hostname = h
} else {
config.Hostname = "localhost"
}
if u, err := user.Current(); err == nil {
config.Message_From = u.Username + "@" + config.Hostname
if u.Name != "" {
config.Message_FromName = u.Name
} else {
config.Message_FromName = u.Username
}
}
if -1 == strings.Index(config.Postmaster, "@") {
config.Postmaster += "@" + config.Hostname
}
syslog.Openlog("go-ssmtp", syslog.LOG_PID, syslog.LOG_USER)
// rewrite os.Args so we can parse -FFrom > -F From
newArgs := []string{os.Args[0]}
for _, arg := range os.Args[1:] {
if len(arg) > 2 && arg[0] == '-' {
newArgs = append(newArgs, arg[0:2], arg[2:])
} else {
newArgs = append(newArgs, arg)
}
}
os.Args = newArgs
var ignoreBool bool
var ignoreString string
flag.BoolVar(&ignoreBool, "i", false, "Ignore dots alone on lines - ignored")
flag.StringVar(&ignoreString, "o", "", "Set option x to the specified - ignored")
flag.BoolVar(&config.Verbose, "v", config.Verbose, "Enable verbose mode")
flag.StringVar(&config.ConfigFile, "C", config.ConfigFile, "Use alternate configuration file")
flag.StringVar(&config.Message_From, "f", config.Message_From, "Manually specify the sender-address of the email")
flag.StringVar(&config.Message_FromName, "F", config.Message_FromName, "Manually specify the sender-name of the email")
flag.StringVar(&config.Message_Subject, "S", config.Message_Subject, "Manually specify the subject of the email")
flag.BoolVar(&config.ScanMessage, "t", config.ScanMessage, "Scan message for recipients")
}
func main() {
flag.Parse()
if config.Message_FromCronDaemon {
config.Message_FromName = "CronDaemon"
}
if err := config.ParseFile(config.ConfigFile); err != nil {
panic("error: parsing configuration: " + err.Error())
}
// Map all local users to Postmaster address
config.Message_To = flag.Args()
for i, to := range config.Message_To {
if -1 == strings.Index(to, "@") {
config.Message_To[i] = config.Postmaster
}
}
if config.Verbose {
fmt.Printf("%#v\n", *config)
}
if len(config.Message_To) == 0 && !config.ScanMessage {
panic("error: no recipients supplied")
}
if m, err := compose(); err != nil {
syslog.Errf("compose: %s", err)
panic("compose: " + err.Error())
} else if c, err := connect(); err != nil {
syslog.Errf("connect: %s", err)
panic("connect: " + err.Error())
} else if err := send(c, m); err != nil {
syslog.Errf("send: %s", err)
panic("send: " + err.Error())
} else {
syslog.Syslogf(syslog.LOG_INFO, "[%s] Sent mail; subject \"%s\"; from %s; to %#v", m.Header["Message-Id"][0], m.Header["Subject"][0], config.Message_From, config.Message_To)
}
if config.Verbose {
fmt.Println("Info: send successful")
}
}