From aeedb48490adec8bb384001e04a2e2b8b5646829 Mon Sep 17 00:00:00 2001 From: Daniil Sliusar Date: Thu, 4 Apr 2019 20:23:25 +0300 Subject: [PATCH] Simple HTTP API to sh's sendmail --- .gitignore | 1 + Makefile | 4 ++++ README.md | 1 + main.go | 65 ++++++++++++++++++++++++++++++++++++++++++++++++++++++ 4 files changed, 71 insertions(+) create mode 100644 .gitignore create mode 100644 Makefile create mode 100644 README.md create mode 100644 main.go diff --git a/.gitignore b/.gitignore new file mode 100644 index 0000000..ba077a4 --- /dev/null +++ b/.gitignore @@ -0,0 +1 @@ +bin diff --git a/Makefile b/Makefile new file mode 100644 index 0000000..148512c --- /dev/null +++ b/Makefile @@ -0,0 +1,4 @@ +build: + env CGO_ENABLED=0 GOOS=linux GOARCH=amd64 go build -o ./bin/sendmail-http +clean: + rm ./bin/sendmail-http diff --git a/README.md b/README.md new file mode 100644 index 0000000..3e77b1e --- /dev/null +++ b/README.md @@ -0,0 +1 @@ +Simple http to sendmail diff --git a/main.go b/main.go new file mode 100644 index 0000000..d5cf4c7 --- /dev/null +++ b/main.go @@ -0,0 +1,65 @@ +package main + +import ( + "fmt" + "net/http" + "os" + "os/exec" + + "github.com/labstack/echo" + "github.com/labstack/echo/middleware" +) + +type mailReq struct { + From string `query:"from"` + To string `query:"to"` + Subject string `query:"subject"` + Body string `query:"body"` +} + +func callSendmail(req mailReq) error { + line := fmt.Sprintf("From: %s\\nTo: %s\\nSubject: %s\\n\\n%s", + req.From, req.To, req.Subject, req.Body) + c1 := exec.Command("echo", "-e", line) + c2 := exec.Command("sendmail", req.To) + c2.Stdin, _ = c1.StdoutPipe() + c2.Stdout = os.Stdout + _ = c2.Start() + _ = c1.Run() + _ = c2.Wait() + return nil +} + +func main() { + + var serverAddr = os.Getenv("SERVER_ADDR") + if len(serverAddr) == 0 { + panic("Server address must not be empty") + } + + e := echo.New() + e.Use(middleware.Recover()) + + api_group := e.Group("/api") + + api_group.GET("/sendmail", func(c echo.Context) error { + + req := mailReq{} + if err := c.Bind(&req); err != nil { + return c.JSON(http.StatusBadRequest, map[string]string{ + "status": "error", + "desc": err.Error(), + }) + } + callSendmail(req) + return c.JSON(http.StatusOK, map[string]string{ + "status": "ok", + }) + }) + + err := e.Start(serverAddr) + if err != nil { + panic(err.Error()) + } + +}