GoBlog/contact.go

95 lines
2.6 KiB
Go
Raw Normal View History

2021-07-22 11:41:52 +00:00
package main
import (
"bytes"
"fmt"
"log"
"net/http"
"net/smtp"
"strconv"
"time"
)
const defaultContactPath = "/contact"
func (a *goBlog) serveContactForm(w http.ResponseWriter, r *http.Request) {
blog, bc := a.getBlog(r)
cc := bc.Contact
2021-07-22 11:41:52 +00:00
a.render(w, r, templateContact, &renderData{
BlogString: blog,
Data: map[string]interface{}{
"title": cc.Title,
"description": cc.Description,
2021-07-22 12:04:46 +00:00
"privacy": cc.PrivacyPolicy,
2021-07-22 11:41:52 +00:00
},
})
}
func (a *goBlog) sendContactSubmission(w http.ResponseWriter, r *http.Request) {
// Get blog
blog, bc := a.getBlog(r)
// Get form values and build message
var message bytes.Buffer
2021-07-22 11:41:52 +00:00
// Message
2021-09-01 09:14:49 +00:00
formMessage := cleanHTMLText(r.FormValue("message"))
2021-07-22 11:41:52 +00:00
if formMessage == "" {
a.serveError(w, r, "Message is empty", http.StatusBadRequest)
return
}
// Name
if formName := cleanHTMLText(r.FormValue("name")); formName != "" {
_, _ = fmt.Fprintf(&message, "Name: %s\n", formName)
2021-07-22 11:41:52 +00:00
}
// Email
formEmail := cleanHTMLText(r.FormValue("email"))
2021-07-22 11:41:52 +00:00
if formEmail != "" {
_, _ = fmt.Fprintf(&message, "Email: %s\n", formEmail)
2021-07-22 11:41:52 +00:00
}
// Website
if formWebsite := cleanHTMLText(r.FormValue("website")); formWebsite != "" {
_, _ = fmt.Fprintf(&message, "Website: %s\n", formWebsite)
2021-07-22 11:41:52 +00:00
}
// Add line break if message is not empty
2021-07-22 11:41:52 +00:00
if message.Len() > 0 {
_, _ = fmt.Fprintf(&message, "\n")
2021-07-22 11:41:52 +00:00
}
// Add message text to message
2021-07-22 11:41:52 +00:00
_, _ = message.WriteString(formMessage)
// Send submission
if err := a.sendContactEmail(bc.Contact, message.String(), formEmail); err != nil {
log.Println(err.Error())
2021-07-22 11:41:52 +00:00
}
// Send notification
a.sendNotification(message.String())
// Give feedback
a.render(w, r, templateContact, &renderData{
BlogString: blog,
Data: map[string]interface{}{
"sent": true,
},
})
}
func (a *goBlog) sendContactEmail(cc *configContact, body, replyTo string) error {
// Check required config
if cc == nil || cc.SMTPHost == "" || cc.EmailFrom == "" || cc.EmailTo == "" {
return fmt.Errorf("email not send as config is missing")
}
// Build email
var email bytes.Buffer
_, _ = fmt.Fprintf(&email, "To: %s\n", cc.EmailTo)
if replyTo != "" {
_, _ = fmt.Fprintf(&email, "Reply-To: %s\n", replyTo)
}
_, _ = fmt.Fprintf(&email, "Date: %s\n", time.Now().UTC().Format(time.RFC1123Z))
_, _ = fmt.Fprintf(&email, "Subject: New message\n\n")
_, _ = fmt.Fprintf(&email, "%s\n", body)
// Send email using SMTP
auth := smtp.PlainAuth("", cc.SMTPUser, cc.SMTPPassword, cc.SMTPHost)
port := cc.SMTPPort
if port == 0 {
port = 587
}
return smtp.SendMail(cc.SMTPHost+":"+strconv.Itoa(port), auth, cc.EmailFrom, []string{cc.EmailTo}, email.Bytes())
}