You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
 
 

89 lines
2.1 KiB

package main
import (
"fmt"
"log"
"net/http"
"os"
"encoding/json"
"strconv"
"github.com/joho/godotenv"
"gopkg.in/gomail.v2"
)
func loadEnv() {
err := godotenv.Load()
if err != nil {
log.Fatal("Error loading .env file")
}
}
func frontEndHandler(w http.ResponseWriter, r *http.Request) {
w.Header().Set("Content-Type", "text/html; charset=utf-8")
fmt.Fprint(w, "<h1>M A I L?!?!?!?!?!</h1>")
}
func healthCheckHandler(w http.ResponseWriter, r *http.Request) {
w.WriteHeader(http.StatusOK)
w.Write([]byte("Health Check"))
}
func mailHandler(w http.ResponseWriter, r *http.Request) {
if r.Method == http.MethodOptions {
w.Header().Set("Access-Control-Allow-Origin", "*")
w.Header().Set("Access-Control-Allow-Methods", "POST")
w.Header().Set("Access-Control-Allow-Headers", "Content-Type")
w.Header().Set("Access-Control-Max-Age", "3600")
w.WriteHeader(http.StatusNoContent)
return
}
token := r.URL.Query().Get("token")
if (token == os.Getenv("SECURE_TOKEN") || os.Getenv("SECURE_TOKEN") == "") && r.Method == http.MethodPost {
type Request struct {
Sendto string
Subject string
Body string
}
var reqItems Request
_ = json.NewDecoder(r.Body).Decode(&reqItems)
m := gomail.NewMessage()
m.SetHeader("From", os.Getenv("SMTP_FROM_EMAIL"))
m.SetHeader("To", reqItems.Sendto)
m.SetHeader("Subject", reqItems.Subject)
m.SetBody("text/html", reqItems.Body)
port, _ := strconv.Atoi(os.Getenv("SMTP_PORT"))
d := gomail.NewDialer(os.Getenv("SMTP_HOST"), port, os.Getenv("SMTP_USERNAME"), os.Getenv("SMTP_PASSWORD"))
if err := d.DialAndSend(m); err != nil {
panic(err)
}
w.Header().Set("Access-Control-Allow-Origin", "*")
w.Header().Set("Access-Control-Allow-Methods", "POST")
} else {
w.WriteHeader(http.StatusUnauthorized)
w.Write([]byte("401 - Unauthorized!"))
}
}
func main() {
loadEnv()
http.HandleFunc("/", frontEndHandler)
http.HandleFunc("/api/healthcheck", healthCheckHandler)
http.HandleFunc("/api/sendmail", mailHandler)
log.Println("Listening on :3000...")
err := http.ListenAndServe(":3000", nil)
if err != nil {
log.Fatal(err)
}
}