-
Notifications
You must be signed in to change notification settings - Fork 3
/
smtp.go
98 lines (85 loc) · 2.08 KB
/
smtp.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
package mailKit
import (
"fmt"
"github.com/jordan-wright/email"
"github.com/richelieu-yang/chimera/v3/src/consts"
"github.com/richelieu-yang/chimera/v3/src/core/errorKit"
"github.com/richelieu-yang/chimera/v3/src/core/strKit"
"net/smtp"
"sync"
"time"
)
type (
SmtpConfig struct {
// e.g. "smtp.163.com:25"
Address string
// e.g. "smtp.163.com"
Host string
// 邮箱账号
Account string
// 邮箱的授权码
Password string
// 发件人的昵称(默认: consts.ProjectName)
NickName string
}
)
var smtpLock = &sync.RWMutex{}
var smtpPool *email.Pool
var defaultFrom string
// InitializeSmtp
/*
e.g.
初始化传参count为2,同时发10条邮件,并不会丢失邮件,10条邮件都会被正常发出去.
*/
func InitializeSmtp(config *SmtpConfig, count int) error {
smtpLock.Lock()
defer smtpLock.Unlock()
if config == nil {
return errorKit.Newf("config == nil")
}
config.NickName = strKit.EmptyToDefault(config.NickName, consts.ProjectName, true)
defaultFrom = fmt.Sprintf("%s <%s>", config.NickName, config.Account)
if count <= 0 {
return errorKit.Newf("count(%d) is invalid", count)
}
auth := smtp.PlainAuth("", config.Account, config.Password, config.Host)
if p, err := email.NewPool(config.Address, count, auth); err != nil {
smtpPool = nil
return err
} else {
smtpPool = p
return nil
}
}
// Dispose 释放资源
func Dispose() {
smtpLock.Lock()
defer smtpLock.Unlock()
if smtpPool != nil {
smtpPool.Close()
smtpPool = nil
}
}
func NewMail(from string, to []string, subject string, text, html []byte, cc, bcc []string) *email.Email {
mail := email.NewEmail()
mail.From = from
mail.To = to
mail.Subject = subject
mail.Text = text
mail.HTML = html
mail.Cc = cc
mail.Bcc = bcc
return mail
}
func SendMail(mail *email.Email) error {
smtpLock.RLock()
defer smtpLock.RUnlock()
if smtpPool == nil {
return errorKit.Newf("smtp pool hasn't been initialized")
}
if mail == nil {
return errorKit.Newf("mail == nil")
}
mail.From = strKit.EmptyToDefault(mail.From, defaultFrom, true)
return smtpPool.Send(mail, time.Second*6)
}