-
Notifications
You must be signed in to change notification settings - Fork 0
/
email.go
83 lines (71 loc) · 1.89 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
package email
import (
"embed"
"fmt"
"io/ioutil"
"net/smtp"
"os"
"strconv"
"strings"
_ "embed"
"github.com/edgar-care/edgarlib"
)
//go:embed templates/*.html
var embeddedTemplates embed.FS
type Email struct {
To string
Subject string
Body string
Template string
TemplateInfos map[string]interface{}
}
func readHTMLFile(filePath string) (string, error) {
content, err := ioutil.ReadFile(filePath)
if err != nil {
return "", err
}
return string(content), nil
}
func replaceHtmlContent(content string, replacements map[string]interface{}) string {
for key, value := range replacements {
content = strings.Replace(content, "{{."+key+"}}", fmt.Sprintf("%v", value), -1)
}
return content
}
func SendEmail(emailInfo Email) error {
sesSMTPServer := os.Getenv("SES_SMTP_URL")
sesSMTPPort, err := strconv.Atoi(os.Getenv("SES_SMTP_PORT"))
edgarlib.CheckError(err)
sesUsername := os.Getenv("SES_USERNAME")
sesPassword := os.Getenv("SES_PASSWORD")
fromAddress := os.Getenv("SENDER_EMAIL")
var message string
message = fmt.Sprintf("Subject: %s\r\n", emailInfo.Subject)
message += "MIME-version: 1.0;\r\n"
message += "Content-Type: text/html; charset=\"UTF-8\";\r\n\r\n"
if emailInfo.Template == "" {
message += emailInfo.Body
} else {
templateFilePath := fmt.Sprintf("templates/%s.html", emailInfo.Template)
templateContent, err := embeddedTemplates.ReadFile(templateFilePath)
if err != nil {
message += emailInfo.Body
} else {
htmlContent := replaceHtmlContent(string(templateContent), emailInfo.TemplateInfos)
message += htmlContent
}
}
auth := smtp.PlainAuth("", sesUsername, sesPassword, sesSMTPServer)
err = smtp.SendMail(
fmt.Sprintf("%s:%d", sesSMTPServer, sesSMTPPort),
auth,
fromAddress,
[]string{emailInfo.To},
[]byte(message),
)
if err != nil {
fmt.Println("Error sending email:", err)
return err
}
return nil
}