-
Notifications
You must be signed in to change notification settings - Fork 6
/
Copy pathexample_test.go
101 lines (84 loc) · 1.73 KB
/
example_test.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
package mailx
import (
"fmt"
"io"
"net/mail"
"time"
)
// @author valor.
func Sample() {
const (
smtpHost = "smtp.example.com"
smtpPort = 465
username = "user"
password = "123456"
sslOnConnect = true
)
m := NewMessage()
m.SetTo("[email protected]", "[email protected]")
m.SetRcptCc(&mail.Address{Name: "Dan", Address: "[email protected]"})
m.SetSubject("This is a subject of email.")
m.SetPlainBody("This is a text/plain body.")
m.Attach("attach.txt", func(w io.Writer) (int, error) {
return io.WriteString(w, "this is a txt attachment.")
})
d := &Dialer{
Host: smtpHost,
Port: smtpPort,
Username: username,
Password: password,
SSLOnConnect: sslOnConnect,
}
err := d.DialAndSend(m)
if err != nil {
panic(err)
}
}
func SampleDaemon() {
const (
smtpHost = "smtp.example.com"
smtpPort = 465
username = "user"
password = "123456"
sslOnConnect = true
)
// Use the channel in your program to send emails.
ch := make(chan *Message)
go func() {
d := &Dialer{
Host: smtpHost,
Port: smtpPort,
Username: username,
Password: password,
SSLOnConnect: sslOnConnect,
}
var ser *Sender
var err error
open := false
for {
select {
case m := <-ch:
if !open {
if ser, err = d.Dial(); err != nil {
fmt.Printf("%s\n", err.Error())
}
open = true
}
if err := ser.Send(m); err != nil {
fmt.Printf("%s\n", err.Error())
}
// 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 := ser.Close(); err != nil {
fmt.Printf("%s\n", err.Error())
}
open = false
}
}
}
}()
// Close the channel to stop the mail daemon.
close(ch)
}