This repository has been archived by the owner on Mar 1, 2020. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 0
/
apisendemail.go
92 lines (75 loc) · 1.56 KB
/
apisendemail.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
83
84
85
86
87
88
89
90
91
92
package main
import (
"encoding/json"
"fmt"
"github.com/gorilla/mux"
"github.com/naoina/toml"
"html"
"io/ioutil"
"log"
"net/http"
"net/smtp"
"os"
)
// Config represents toml's configuration file
type Config struct {
EmailAccount []struct {
From string
To string
Pass string
}
EmailRoute []struct {
Endpoint string
}
}
// Dat var
var Dat Config
// Contact represents body email...
type Contact struct {
From string `json:"from"`
Body string `json:"body"`
}
func sendEmail(w http.ResponseWriter, r *http.Request) {
fmt.Fprintf(w, "Hello, %q", html.EscapeString(r.URL.Path))
var f, p, t string
f = Dat.EmailAccount[0].From
p = Dat.EmailAccount[0].Pass
t = Dat.EmailAccount[0].To
decoder := json.NewDecoder(r.Body)
var c Contact
var err error
err = decoder.Decode(&c)
if err != nil {
panic(err)
}
msg := "From: " + f + "\n" +
"To: " + t + "\n" +
"Subject: Hello there\n\n" +
"From: " + c.From + "\n\n" +
"Message: " + c.Body
err = smtp.SendMail("smtp.gmail.com:587",
smtp.PlainAuth("", f, p, "smtp.gmail.com"),
f, []string{t}, []byte(msg))
if err != nil {
log.Printf("smtp error: %s", err)
return
}
log.Print("sent...")
}
func main() {
f, err := os.Open("config-apisendemail.toml")
if err != nil {
panic(err)
}
defer f.Close()
buf, err := ioutil.ReadAll(f)
if err != nil {
panic(err)
}
if err := toml.Unmarshal(buf, &Dat); err != nil {
panic(err)
}
router := mux.NewRouter().StrictSlash(true)
router.HandleFunc("/"+Dat.EmailRoute[0].Endpoint, sendEmail)
log.Fatal(http.ListenAndServe(":8080", router))
}