-
Notifications
You must be signed in to change notification settings - Fork 2
/
mail.go
111 lines (95 loc) · 2.29 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
package mail
import (
"fmt"
"log"
"net/smtp"
"time"
//lg "github.com/hiromaily/golibs/log"
"encoding/base64"
//conf "github.com/hiromaily/golibs/config"
)
//TODO:work in progress
//https://gist.github.com/andelf/5004821
// Info is for mail information
type Info struct {
ToAddress []string
FromAddress string
Subject string
Body string
SMTP
}
// SMTP is for SMTP server
type SMTP struct {
Address string
Pass string
Server string
Port int
}
func (ml *Info) makeMailBody() {
//TODO:when toaddress have more one address
header := make(map[string]string)
header["From"] = ml.FromAddress
header["To"] = ml.ToAddress[0] //TODO:temporary
header["Subject"] = ml.Subject
header["MIME-Version"] = "1.0"
header["Content-Type"] = "text/plain; charset=\"utf-8\""
header["Content-Transfer-Encoding"] = "base64"
var message string
for k, v := range header {
message += fmt.Sprintf("%s: %s\r\n", k, v)
}
message += "\r\n" + base64.StdEncoding.EncodeToString([]byte(ml.Body))
//update self.Body
//*self.Body = message
ml.Body = message
}
func (ml *Info) sendMail(c chan bool) {
//co := conf.GetConf().Mail
// Set up authentication information.
// func PlainAuth(identity, username, password, host string) Auth {
auth := smtp.PlainAuth(
"",
ml.Address, // info@gmail.com
ml.Pass, // password
ml.Server, // smtp.xxxx.com
)
//body
ml.makeMailBody()
// Connect to the server, authenticate, set the sender and recipient,
// and send the email all in one step.
// func SendMail(addr string, a Auth, from string, to []string, msg []byte) error {
err := smtp.SendMail(
fmt.Sprintf("%s:%d", ml.Server, ml.Port), // smtp.xxxxx.com:255
auth,
ml.Address, //(from)info@gmail.com
ml.ToAddress, //(to)address
[]byte(ml.Body), //body
)
if err != nil {
log.Fatal(err)
c <- false
return
}
c <- true
}
// SendMail is to send mail
func (ml *Info) SendMail(timeOut string) {
emailTimeout, _ := time.ParseDuration(timeOut) //10s
c := make(chan bool)
//send mail
//for handling timeout using goroutine.
go ml.sendMail(c)
fmt.Println("start to wait")
select {
case bRet := <-c:
//it may be ok
if bRet {
fmt.Println("succeeded")
} else {
fmt.Println("failed")
}
case <-time.After(emailTimeout):
//timeout code
fmt.Println("timeout")
}
}