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
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134 | package email
import (
"fmt"
"strings"
"gopkg.in/gomail.v2"
)
type TextType int
const (
TEXT TextType = iota
HTML
IMAGE
)
type email struct {
NickName string
UserName string
Passport string
Host string
Port int
TO []string
CC []string
AttachMent []string
ImageView struct {
Header string
Footer string
Source string
Link string
}
Type TextType
}
func NewEmail() *email { return &email{} }
func (e *email) SetNickName(nickname string) *email {
e.NickName = nickname
return e
}
func (e *email) SetUserName(username string) *email {
e.UserName = username
return e
}
func (e *email) SetPassport(passport string) *email {
e.Passport = passport
return e
}
func (e *email) SetHost(host string) *email {
e.Host = host
return e
}
func (e *email) SetPort(port int) *email {
e.Port = port
return e
}
func (e *email) SetTo(to ...string) *email {
e.TO = to
return e
}
func (e *email) SetCC(cc ...string) *email {
e.CC = cc
return e
}
func (e *email) SetAttachMent(attach ...string) *email {
e.AttachMent = attach
return e
}
func (e *email) SetImageView(header, footer, source, link string) *email {
e.ImageView.Header = header
e.ImageView.Footer = footer
e.ImageView.Source = source
e.ImageView.Link = link
return e
}
func (e *email) SetType(typ TextType) *email {
e.Type = typ
return e
}
func (e *email) Send(subject, content string) error {
m := gomail.NewMessage()
m.SetHeader("From", m.FormatAddress(e.UserName, e.NickName))
m.SetHeader("To", e.TO...)
m.SetHeader("Cc", e.CC...)
m.SetHeader("Subject", subject)
switch typ := e.Type; typ {
case HTML:
m.SetBody("text/html", content)
case IMAGE:
m.Embed(e.ImageView.Source)
embedNameS := strings.Split(e.ImageView.Source, "/")
embedName := embedNameS[len(embedNameS)-1]
body := fmt.Sprintf(`%s<br/>
%s<br/>
<a href="%s" >
<img src="cid:%s" alt="%s" />
</a>
<br/>%s
`,
e.ImageView.Header,
content,
e.ImageView.Link,
embedName, embedName,
e.ImageView.Footer,
)
m.SetBody("text/html", body)
default:
m.SetBody("text/plain", content)
}
for _, attach := range e.AttachMent {
m.Attach(attach)
}
d := gomail.NewDialer(e.Host, e.Port, e.UserName, e.Passport)
if err := d.DialAndSend(m); err != nil {
return err
}
return nil
}
|