Enhance project functionality: add email template, implement email sending, and improve table management routes
The table management in the database does currently not work
This commit is contained in:
44
src/utils.go
44
src/utils.go
@@ -1,11 +1,18 @@
|
||||
package main
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"crypto/rand"
|
||||
"encoding/hex"
|
||||
"errors"
|
||||
"html/template"
|
||||
"log"
|
||||
"os"
|
||||
"strings"
|
||||
"time"
|
||||
|
||||
"github.com/gin-gonic/gin"
|
||||
"gopkg.in/gomail.v2"
|
||||
)
|
||||
|
||||
func mustRandToken(n int) string {
|
||||
@@ -134,3 +141,40 @@ func stripAfterDot(s string) string {
|
||||
}
|
||||
return s
|
||||
}
|
||||
|
||||
func nameFromEmail(email string) string {
|
||||
parts := strings.SplitN(email, "@", 2)
|
||||
if len(parts) > 0 {
|
||||
return parts[0]
|
||||
}
|
||||
return ""
|
||||
}
|
||||
|
||||
func sendEmail(email string, token string) error {
|
||||
// Parse the email body template
|
||||
tmpl, err := template.ParseFiles("other/email.txt")
|
||||
if err != nil {
|
||||
panic(err)
|
||||
}
|
||||
|
||||
// Execute template with provided data
|
||||
var body bytes.Buffer
|
||||
if err := tmpl.Execute(&body, gin.H{"Token": token, "Name": nameFromEmail(email)}); err != nil {
|
||||
panic(err)
|
||||
}
|
||||
|
||||
// Compose email
|
||||
m := gomail.NewMessage()
|
||||
m.SetHeader("From", os.Getenv("SMTP_MAIL"))
|
||||
m.SetHeader("To", email)
|
||||
m.SetHeader("Subject", "Registration/Login to QRank")
|
||||
m.SetBody("text/plain", body.String())
|
||||
|
||||
// Dial and send
|
||||
d := gomail.NewDialer(os.Getenv("SMTP_HOST"), 587, os.Getenv("SMTP_MAIL"), os.Getenv("SMTP_PASS"))
|
||||
if err := d.DialAndSend(m); err != nil {
|
||||
log.Fatalln(err)
|
||||
return err
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user