forked from toolkits/smtp
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathsmtp.go
74 lines (60 loc) · 1.62 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
package smtp
import (
"encoding/base64"
"fmt"
"net/smtp"
"strings"
)
type Smtp struct {
Address string
Username string
Password string
}
func New(address, username, password string) *Smtp {
return &Smtp{
Address: address,
Username: username,
Password: password,
}
}
func (this *Smtp) SendMail(from, tos, subject, body string, contentType ...string) error {
if this.Address == "" {
return fmt.Errorf("address is necessary")
}
hp := strings.Split(this.Address, ":")
if len(hp) != 2 {
return fmt.Errorf("address format error")
}
arr := strings.Split(tos, ";")
count := len(arr)
safeArr := make([]string, 0, count)
for i := 0; i < count; i++ {
if arr[i] == "" {
continue
}
safeArr = append(safeArr, arr[i])
}
if len(safeArr) == 0 {
return fmt.Errorf("tos invalid")
}
tos = strings.Join(safeArr, ";")
b64 := base64.NewEncoding("ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/")
header := make(map[string]string)
header["From"] = from
header["To"] = tos
header["Subject"] = fmt.Sprintf("=?UTF-8?B?%s?=", b64.EncodeToString([]byte(subject)))
header["MIME-Version"] = "1.0"
ct := "text/plain; charset=UTF-8"
if len(contentType) > 0 && contentType[0] == "html" {
ct = "text/html; charset=UTF-8"
}
header["Content-Type"] = ct
header["Content-Transfer-Encoding"] = "base64"
message := ""
for k, v := range header {
message += fmt.Sprintf("%s: %s\r\n", k, v)
}
message += "\r\n" + b64.EncodeToString([]byte(body))
auth := smtp.PlainAuth("", this.Username, this.Password, hp[0])
return smtp.SendMail(this.Address, auth, from, strings.Split(tos, ";"), []byte(message))
}