-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathsendmail.go
82 lines (68 loc) · 2.03 KB
/
sendmail.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
package main
import (
"bytes"
"fmt"
"html/template"
"net/smtp"
)
type message struct {
Subject string
Recipient string
Sender string
ReplyTo string
Body []byte
}
func buildAndSend(cfg *Config, sub FormSubmission) error {
msg, err := buildEmailMessage(sub)
if err != nil {
fmt.Println("Failed to build email message:", err)
return err
}
err = sendEmail(cfg, msg)
if err != nil {
fmt.Println("Failed to send email:", err)
return err
}
fmt.Println("Email sent successfully!")
return nil
}
func buildEmailMessage(sub FormSubmission) (message, error) {
tmpl := loadTemplate(sub.Id)
var body bytes.Buffer
if err := tmpl.ExecuteTemplate(&body, sub.Id+".html", sub.Body); err != nil {
return message{}, err
}
headers := "From: <" + sub.FormCfg.Mail.Sender + ">\r\n" +
"To: <" + sub.FormCfg.Mail.Recipient + ">\r\n" +
"Subject: " + sub.FormCfg.Mail.Subject + " - " + sub.Id + "\r\n" +
"Reply-To: <" + sub.Body[sub.FormCfg.Fields.Email] + ">\r\n" +
"MIME-version: 1.0;\r\nContent-Type: text/html; charset=\"UTF-8\";\r\n\r\n"
return message{
Subject: sub.FormCfg.Mail.Subject + " - " + sub.Id,
Body: []byte(headers + body.String()),
Recipient: "<" + sub.FormCfg.Mail.Recipient + ">",
Sender: "<" + sub.FormCfg.Mail.Sender + ">",
ReplyTo: sub.Body[sub.FormCfg.Fields.Email],
}, nil
}
func sendEmail(cfg *Config, message message) error {
auth := smtp.PlainAuth("", cfg.Smtp.User, cfg.Smtp.Password, cfg.Smtp.Host)
err := smtp.SendMail(fmt.Sprintf("%s:%d", cfg.Smtp.Host, cfg.Smtp.Port), auth, message.Sender, []string{message.Recipient}, message.Body)
if err != nil {
return err
}
return nil
}
func loadTemplate(id string) *template.Template {
defaultTemplate, err := template.New("default").ParseFiles("forms/default.html")
if err != nil {
fmt.Println("Failed to parse default template:", err)
return nil
}
template, err := template.ParseFiles(fmt.Sprintf("forms/%s.html", id))
if err != nil {
fmt.Println("Failed to parse template:", err)
return defaultTemplate
}
return template
}