forked from uadmin/uadmin
-
Notifications
You must be signed in to change notification settings - Fork 1
/
send_email.go
53 lines (45 loc) · 1.48 KB
/
send_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
package uadmin
import (
"fmt"
"net/smtp"
"strings"
"time"
)
// SendEmail sends email using system configured variables
func SendEmail(to, cc, bcc []string, subject, body string) (err error) {
if EmailFrom == "" || EmailPassword == "" || EmailSMTPServer == "" || EmailSMTPServerPort == 0 {
errMsg := "Email not sent because email global variables are not set."
Trail(WARNING, err)
return fmt.Errorf(errMsg)
}
// Get the domain name of sender
domain := strings.Split(EmailFrom, "@")
if len(domain) < 2 {
return
}
domain[0] = strings.TrimSpace(domain[0])
domain[0] = strings.TrimSuffix(domain[0], ">")
// Construct the email
msg := "From: " + EmailFrom + "\r\n"
msg += "To: " + strings.Join(to, ",") + "\r\n"
if len(cc) > 0 {
msg += "CC: " + strings.Join(cc, ",") + "\r\n"
}
msg += "Date: " + time.Now().UTC().Format(time.RFC1123Z) + "\r\n"
msg += "Message-ID: " + fmt.Sprintf("<%s-%s-%s-%s-%s@%s>", GenerateBase32(8), GenerateBase32(4), GenerateBase32(4), GenerateBase32(4), GenerateBase32(12), domain[0]) + "\r\n"
msg += "Subject: " + subject + "\r\n\r\n"
msg += strings.Replace(body, "\n", "\r\n", -1)
msg += "\r\n"
// Append CC and BCC
to = append(to, cc...)
to = append(to, bcc...)
go func() {
err = smtp.SendMail(fmt.Sprintf("%s:%d", EmailSMTPServer, EmailSMTPServerPort),
smtp.PlainAuth("", EmailUsername, EmailPassword, EmailSMTPServer),
EmailFrom, to, []byte(msg))
if err != nil {
Trail(WARNING, "Email was not sent. %s", err)
}
}()
return nil
}