This repository has been archived by the owner on Aug 25, 2021. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 0
/
smtp.go
75 lines (64 loc) · 1.39 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
package smtp
import (
"net"
"net/smtp"
)
// Mail smtp adapter
type Mail struct {
username string
password string
host string
from string
}
// Option option mail field
type Option func(*Mail)
// WithUsername set username
func WithUsername(username string) Option {
return func(m *Mail) {
m.username = username
}
}
// WithPassword set password
func WithPassword(password string) Option {
return func(m *Mail) {
m.password = password
}
}
// WithHost set host
func WithHost(host string) Option {
return func(m *Mail) {
m.host = host
}
}
// WithFrom set from
func WithFrom(from string) Option {
return func(m *Mail) {
m.from = from
}
}
// NewSMTP return a opened *Mail
func NewSMTP(opt ...Option) *Mail {
m := new(Mail)
for _, o := range opt {
o(m)
}
return m
}
// Send use smtp send email
// to := []string{"recipient@example.net"}
// msg := []byte("To: recipient@example.net\r\n" +
// "Subject: discount Gophers!\r\n" +
// "\r\n" +
// "This is the email body.\r\n")
// err := smtp.SendMail("mail.example.com:25", auth, "sender@example.org", to, msg)
// if err != nil {
// log.Fatal(err)
// }
func (m *Mail) Send(to []string, msg string) error {
host, port, err := net.SplitHostPort(m.host)
if err != nil {
return err
}
auth := smtp.PlainAuth("", m.username, m.password, host)
return smtp.SendMail(net.JoinHostPort(host, port), auth, m.from, to, []byte(msg))
}