This repository has been archived by the owner on Oct 4, 2020. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathgomail.go
91 lines (74 loc) · 2.21 KB
/
gomail.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
package email
import (
"crypto/tls"
"log"
"strconv"
"gopkg.in/gomail.v2"
)
// GoMailClient manage all GoMail action
type GoMailClient struct {
dialer *gomail.Dialer
session gomail.SendCloser
url string
portNumber string
username string
password string
}
// NewGoEmailClient function return GoMail client based on singleton pattern
func NewGoEmailClient(url, portNumber, username, password string) IMailClient {
currentSession := &GoMailClient{nil, nil, "", "", "", ""}
dialer, err := getDialer(url, portNumber, username, password)
if err != nil {
log.Println("Error when try to make strconv port from config: ", err)
panic(err)
}
session, err := dialer.Dial()
if err != nil {
log.Println("Error when try to dial to mail server: ", err)
panic(err)
}
log.Println("Connected to Mail Server")
currentSession.dialer = dialer
currentSession.session = session
currentSession.url = url
currentSession.portNumber = portNumber
currentSession.username = username
currentSession.password = password
return currentSession
}
// Send function sent mail based on argument provide
func (e *GoMailClient) Send(from, to, subject, message string) (err error) {
msg := gomail.NewMessage()
msg.SetHeader("From", from)
msg.SetAddressHeader("To", to, "")
msg.SetHeader("Subject", subject)
msg.SetBody("text/html", message)
if e.session != nil {
if err = e.session.Send(from, []string{to}, msg); err != nil {
// close current session
e.session.Close()
// generate new client
e.dialer, _ = getDialer(e.url, e.portNumber, e.username, e.password)
// reconnect smtp server
if newSession, err := e.dialer.Dial(); err == nil {
e.session = newSession
// resend email
return e.session.Send(from, []string{to}, msg)
}
return err
}
return nil
}
return e.dialer.DialAndSend(msg)
}
// getDialer private function return a new Dialer
func getDialer(url, portNumber, username, password string) (client *gomail.Dialer, err error) {
port, err := strconv.Atoi(portNumber)
if err != nil {
return nil, err
}
client = gomail.NewDialer(url, port, username, password)
client.TLSConfig = &tls.Config{InsecureSkipVerify: true, ServerName: url}
client.LocalName = url
return client, nil
}