-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathemail.go
130 lines (109 loc) · 2.49 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
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
package pkgscens
import (
"encoding/base64"
"fmt"
"net/smtp"
"strings"
)
//SMTPAuth def
type SMTPAuth struct {
Identity string
Username string
Password string
Host string
}
//SendMailInput struct
type SendMailInput struct {
Addr string
SMTPAuth SMTPAuth
FromName string
FromMail string
ToMail []string
ToName []string
Subject string
MsgType string
Message string
}
//SendMail func
func SendMail(sendMailInput SendMailInput) error {
auth := smtp.PlainAuth(
"",
sendMailInput.SMTPAuth.Username,
sendMailInput.SMTPAuth.Password,
sendMailInput.SMTPAuth.Host,
)
if sendMailInput.FromMail == "" {
return &PkgError{
Msg: "empty from mail",
}
}
if len(sendMailInput.ToMail) != len(sendMailInput.ToName) {
return &PkgError{
Msg: "email_to_name_must_match_with_to_email",
}
}
if sendMailInput.Subject == "" {
return &PkgError{
Msg: "Empty Subject",
}
}
msgType := ""
if sendMailInput.MsgType != "TEXT" && sendMailInput.MsgType != "HTML" {
if sendMailInput.MsgType == "" {
msgType = "TEXT"
} else {
return &PkgError{
Msg: "MsgType Error",
}
}
} else {
msgType = sendMailInput.MsgType
}
var recipientMail []string
var toHeaderMail []string
// to email process
if len(sendMailInput.ToMail) != 0 {
for index, to := range sendMailInput.ToMail {
str := sendMailInput.ToName[index] + " <" + to + ">"
toHeaderMail = append(toHeaderMail, str)
recipientMail = append(recipientMail, to)
}
}
toHeader := strings.Join(toHeaderMail, ",")
header := make(map[string]string)
header["MIME-Version"] = "1.0"
header["Content-Transfer-Encoding"] = "base64"
header["From"] = sendMailInput.FromName + " <" + sendMailInput.FromMail + ">"
header["Subject"] = sendMailInput.Subject
if msgType == "HTML" {
header["Content-Type"] = "text/html; charset=\"utf-8\""
} else {
header["Content-Type"] = "text/plain; charset=\"utf-8\""
}
if toHeader != "" {
header["To"] = toHeader
}
msg := ""
for k, v := range header {
msg += fmt.Sprintf("%s: %s\r\n", k, v)
}
msg += "\r\n" + base64.StdEncoding.EncodeToString([]byte(sendMailInput.Message))
err := smtp.SendMail(
sendMailInput.Addr, // server:port
auth, // auth
sendMailInput.FromMail, // from email_address
recipientMail, // to []email_address
[]byte(msg), // msg content_here
)
if err != nil {
return err
}
return nil
}
//PkgError Type
type PkgError struct {
Msg string
}
func (m *PkgError) Error() string {
return m.Msg
}