server address verification

simple Email address check for from & to
default port=25 for server address
This commit is contained in:
LetMyPplGo 2019-09-06 00:53:23 +03:00
parent 8f953dabe5
commit fb8aac38dd

View File

@ -18,6 +18,7 @@ import (
"strings"
)
// SMTP is the structure for smtp connection
type SMTP struct {
Address string
Username string
@ -38,35 +39,45 @@ func New(address, username, password string) *SMTP {
// and then sends an email from address from, to addresses to, with
// message msg.
func (s *SMTP) SendMail(from, tos, subject, body string, contentType ...string) error {
if s.Address == "" {
return fmt.Errorf("address is necessary")
}
server := ""
address := ""
hp := strings.Split(s.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
if (s.Address == "") || (len(hp) > 2) {
return fmt.Errorf("Server address is either empty or incorrect: %s", s.Address)
} else if len(hp) == 1 {
server = s.Address
address = server + ":25"
} else if len(hp) == 2 {
if (hp[0] == "") || (hp[1] == "") {
return fmt.Errorf("Server address is either empty or incorrect: %s", s.Address)
}
safeArr = append(safeArr, arr[i])
server = hp[0]
address = s.Address
}
if len(safeArr) == 0 {
return fmt.Errorf("tos invalid")
tosArr := []string{}
arr := strings.Split(tos, ";")
for _, to := range arr {
// TODO: replace with regex
if strings.Contains(to, "@") {
tosArr = append(tosArr, to)
}
}
if len(tosArr) == 0 {
return fmt.Errorf("tos if invalid: %s", tos)
}
if !strings.Contains(from, "@") {
return fmt.Errorf("from is invalid: %s", from)
}
tos = strings.Join(safeArr, ";")
b64 := base64.NewEncoding("ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/")
header := make(map[string]string)
header["From"] = from
header["To"] = tos
header["To"] = strings.Join(tosArr, ";")
header["Subject"] = fmt.Sprintf("=?UTF-8?B?%s?=", b64.EncodeToString([]byte(subject)))
header["MIME-Version"] = "1.0"
@ -84,6 +95,6 @@ func (s *SMTP) SendMail(from, tos, subject, body string, contentType ...string)
}
message += "\r\n" + b64.EncodeToString([]byte(body))
auth := smtp.PlainAuth("", s.Username, s.Password, hp[0])
return smtp.SendMail(s.Address, auth, from, strings.Split(tos, ";"), []byte(message))
auth := smtp.PlainAuth("", s.Username, s.Password, server)
return smtp.SendMail(address, auth, from, tosArr, []byte(message))
}