forked from chanyipiaomiao/hltool
/
email.go
89 lines (77 loc) · 1.84 KB
/
email.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
package hltool
import (
"crypto/tls"
"gopkg.in/gomail.v2"
)
// EmailMessage 内容
type EmailMessage struct {
From string
To []string
Cc []string
Subject string
ContentType string
Content string
Attach string
}
// NewEmailMessage 返回消息对象
// from: 发件人
// subject: 标题
// contentType: 内容的类型 text/plain text/html
// attach: 附件
// to: 收件人
// cc: 抄送人
func NewEmailMessage(from, subject, contentType, content, attach string, to, cc []string) *EmailMessage {
return &EmailMessage{
From: from,
Subject: subject,
ContentType: contentType,
Content: content,
To: to,
Cc: cc,
Attach: attach,
}
}
// EmailClient 发送客户端
type EmailClient struct {
Host string
Port int
Username string
Password string
Message *EmailMessage
}
// NewEmailClient 返回一个邮件客户端
// host smtp地址
// username 用户名
// password 密码
// port 端口
func NewEmailClient(host, username, password string, port int, message *EmailMessage) *EmailClient {
return &EmailClient{
Host: host,
Port: port,
Username: username,
Password: password,
Message: message,
}
}
// SendMessage 发送邮件
func (c *EmailClient) SendMessage() (bool, error) {
e := gomail.NewPlainDialer(c.Host, c.Port, c.Username, c.Password)
if 587 == c.Port {
e.TLSConfig = &tls.Config{InsecureSkipVerify: true}
}
dm := gomail.NewMessage()
dm.SetHeader("From", c.Message.From)
dm.SetHeader("To", c.Message.To...)
if len(c.Message.Cc) != 0 {
dm.SetHeader("Cc", c.Message.Cc...)
}
dm.SetHeader("Subject", c.Message.Subject)
dm.SetBody(c.Message.ContentType, c.Message.Content)
if c.Message.Attach != "" {
dm.Attach(c.Message.Attach)
}
if err := e.DialAndSend(dm); err != nil {
return false, err
}
return true, nil
}