-
Notifications
You must be signed in to change notification settings - Fork 4
/
Copy pathgoemail.go
104 lines (85 loc) · 2.77 KB
/
goemail.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
package goemail
import (
"strings"
"github.com/go-gomail/gomail"
)
type EmailParam struct {
// ServerHost 邮箱服务器地址,如腾讯企业邮箱为smtp.exmail.qq.com
ServerHost string
// ServerPort 邮箱服务器端口,如腾讯企业邮箱为465
ServerPort int
// FromEmail 发件人邮箱地址
FromEmail string
// FromPasswd 发件人邮箱密码(注意,这里是明文形式),TODO:如果设置成密文?
FromPasswd string
// Toers 接收者邮件,如有多个,则以英文逗号(“,”)隔开,不能为空
Toers string
// CCers 抄送者邮件,如有多个,则以英文逗号(“,”)隔开,可以为空
CCers string
}
// 全局变量,因为发件人账号、密码,需要在发送时才指定
// 注意,由于是小写,外面的包无法使用
var serverHost, fromEmail, fromPasswd string
var serverPort int
var m *gomail.Message
func InitEmail(ep *EmailParam) {
toers := []string{}
serverHost = ep.ServerHost
serverPort = ep.ServerPort
fromEmail = ep.FromEmail
fromPasswd = ep.FromPasswd
m = gomail.NewMessage()
if len(ep.Toers) == 0 {
return
}
for _, tmp := range strings.Split(ep.Toers, ",") {
toers = append(toers, strings.TrimSpace(tmp))
}
// 收件人可以有多个,故用此方式
m.SetHeader("To", toers...)
//抄送列表
if len(ep.CCers) != 0 {
for _, tmp := range strings.Split(ep.CCers, ",") {
toers = append(toers, strings.TrimSpace(tmp))
}
m.SetHeader("Cc", toers...)
}
// 发件人
// 第三个参数为发件人别名,如"李大锤",可以为空(此时则为邮箱名称)
m.SetAddressHeader("From", fromEmail, "")
}
// SendEmail body支持html格式字符串
func SendEmail(subject, body string) {
// 主题
m.SetHeader("Subject", subject)
// 正文
m.SetBody("text/html", body)
d := gomail.NewPlainDialer(serverHost, serverPort, fromEmail, fromPasswd)
// 发送
err := d.DialAndSend(m)
if err != nil {
panic(err)
}
}
func main111() {
serverHost := "smtp.exmail.qq.com"
serverPort := 465
fromEmail := "[email protected]"
fromPasswd := "1qaz@WSX"
myToers := "[email protected], [email protected]" // 逗号隔开
myCCers := "" //"[email protected]"
subject := "这是主题"
body := `这是正文<br>
Hello <a href = "http://www.latelee.org">主页</a>`
// 结构体赋值
myEmail := &EmailParam {
ServerHost: serverHost,
ServerPort: serverPort,
FromEmail: fromEmail,
FromPasswd: fromPasswd,
Toers: myToers,
CCers: myCCers,
}
InitEmail(myEmail)
SendEmail(subject, body)
}