-
Notifications
You must be signed in to change notification settings - Fork 4
/
email.go
96 lines (86 loc) · 1.92 KB
/
email.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
package webca
import (
"fmt"
"net/smtp"
"strings"
)
const (
MAIL_LABEL = "WebCA"
)
type Mailer struct {
Server, User, Passwd string
bestAuth smtp.Auth
}
func (m *Mailer) SendMail(to, subject, body string) error {
host := m.Server
if strings.Contains(host, ":") {
host = strings.Split(host, ":")[0]
}
//log.Println("host=",host)
auths := []smtp.Auth{m.bestAuth}
msg := "from: \"" + MAIL_LABEL + "\" <" + m.User + ">\nto: " + to +
"\nsubject: (" + MAIL_LABEL + ") " + subject + "\n\n" + body
if m.bestAuth == nil {
auths = []smtp.Auth{smtp.CRAMMD5Auth(m.User, m.Passwd),
smtp.PlainAuth("", m.User, m.Passwd, host)}
}
var errs error
for _, auth := range auths {
err := smtp.SendMail(m.Server, auth, m.User, []string{to}, ([]byte)(msg))
if err == nil {
m.bestAuth = auth
return nil
} else {
errs = fmt.Errorf("%v%v\n", errs, err)
}
}
return errs
}
/*
func read(msg string, ptr interface{}) {
fmt.Print(msg)
os.Stdout.Sync()
fmt.Scan(ptr)
}
func ask() Mailer {
mailer := Mailer{}
read("Mail Server: ", &mailer.Server)
read(" Email user: ", &mailer.User)
read(" Password: ", &mailer.Passwd)
f, err := os.OpenFile(MAILCFG_FILE, os.O_WRONLY|os.O_CREATE|os.O_TRUNC, 0600)
handleFatal(err)
defer f.Close()
enc := gob.NewEncoder(f)
err = enc.Encode(mailer)
handleFatal(err)
return mailer
}
func setup() Mailer {
_, err := os.Stat(MAILCFG_FILE)
if os.IsNotExist(err) {
return ask()
}
handleFatal(err)
f, err := os.Open(MAILCFG_FILE)
handleFatal(err)
defer f.Close()
dec := gob.NewDecoder(f)
if dec == nil {
log.Fatalf("(Warning) Could not decode " + MAILCFG_FILE + "!")
}
mailer := Mailer{}
err = dec.Decode(&mailer)
handleFatal(err)
return mailer
}
func main() {
subject:="Test notification"
to:="[email protected]"
err:=mailer.sendMail(to, subject, "Notification!")
if err!=nil {
log.Fatal(err)
} else {
log.Print("Mail '"+subject+"' Sent to "+to)
}
}
*/