forked from nanjishidu/gomini
-
Notifications
You must be signed in to change notification settings - Fork 0
/
mail.go
114 lines (110 loc) · 2.4 KB
/
mail.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
package gomini
import (
"crypto/tls"
"log"
"time"
gomail "gopkg.in/gomail.v2"
)
type Mail struct {
host string
username string
password string
port int
dialer *gomail.Dialer
messageChan chan *gomail.Message
}
func NewMail(host string, port int, username, password string, num ...int64) *Mail {
var messageChanBuffer int64
if len(num) > 0 {
messageChanBuffer = num[0]
} else {
messageChanBuffer = 1
}
return &Mail{
host: host,
username: username,
password: password,
port: port,
dialer: gomail.NewDialer(host, port, username, password),
messageChan: make(chan *gomail.Message, messageChanBuffer),
}
}
func (m *Mail) SetMessage(params map[string]interface{}) {
msg := gomail.NewMessage()
msg.SetHeader("From", m.username)
if v, ok := params["to"]; ok {
msg.SetHeader("To", v.([]string)...)
}
if v, ok := params["cc"]; ok {
msg.SetHeader("Cc", v.([]string)...)
}
if v, ok := params["bcc"]; ok {
msg.SetHeader("BCc", v.([]string)...)
}
if v, ok := params["x-to"]; ok {
msg.SetHeader("X-To", v.([]string)...)
}
if v, ok := params["subject"]; ok {
msg.SetHeader("Subject", v.(string))
}
if v, ok := params["plain"]; ok {
msg.SetBody("text/plain", v.(string))
}
if v, ok := params["html"]; ok {
msg.SetBody("text/html", v.(string))
}
if v, ok := params["alternative"]; ok {
msg.AddAlternative("text/html", v.(string))
}
if v, ok := params["attach"]; ok {
for _, v2 := range v.([]string) {
msg.Attach(v2)
}
}
if v, ok := params["embed"]; ok {
for _, v2 := range v.([]string) {
msg.Embed(v2)
}
}
m.messageChan <- msg
}
func (m *Mail) SendEmailDaemon() {
var (
s gomail.SendCloser
err error
open = false
)
for {
select {
case msg, ok := <-m.messageChan:
if !ok || msg == nil {
return
}
if !open {
if s, err = m.dialer.Dial(); err != nil {
panic(err)
}
open = true
}
if err := gomail.Send(s, msg); err != nil {
log.Print(err)
}
// Close the connection to the SMTP server if no email was sent in
// the last 30 seconds.
case <-time.After(30 * time.Second):
if open {
if err := s.Close(); err != nil {
panic(err)
}
open = false
}
}
}
}
func (m *Mail) SendEmailOnce() error {
m.dialer.TLSConfig = &tls.Config{InsecureSkipVerify: true}
if msg, ok := <-m.messageChan; ok && msg != nil {
return m.dialer.DialAndSend(msg)
}
return nil
}