Du kan inte välja fler än 25 ämnen Ämnen måste starta med en bokstav eller siffra, kan innehålla bindestreck ('-') och vara max 35 tecken långa.

113 lines
2.3KB

  1. package main
  2. import (
  3. "encoding/json"
  4. "fmt"
  5. log "github.com/sirupsen/logrus"
  6. "net/http"
  7. "net/smtp"
  8. "strings"
  9. )
  10. const formPrefix = "/form/"
  11. type formInput struct {
  12. w http.ResponseWriter
  13. r *http.Request
  14. }
  15. func formMain(w http.ResponseWriter, r *http.Request) {
  16. fi := formInput{w, r}
  17. fi.contactUs()
  18. }
  19. func (m *formInput) contactUs() {
  20. ret := map[string]interface{}{}
  21. ret["success"] = true
  22. // e := m.r.ParseForm()
  23. e := m.r.ParseMultipartForm(32 * 1024 * 1024)
  24. if e != nil {
  25. return
  26. }
  27. for key, values := range m.r.Form { // range over map
  28. for _, value := range values { // range over []string
  29. fmt.Println(key, value)
  30. }
  31. }
  32. name := m.r.FormValue("name")
  33. email := m.r.FormValue("email")
  34. message := m.r.FormValue("message")
  35. ret["name"] = name
  36. ret["email"] = email
  37. ret["message"] = message
  38. m.apiV1SendJson(ret)
  39. go sendContactUs(name, email, message)
  40. }
  41. func (m *formInput) apiV1SendJson(result interface{}) {
  42. //general setup
  43. m.w.Header().Set("Content-Type", "application/json;charset=UTF-8")
  44. out, e := json.Marshal(result)
  45. if e != nil {
  46. log.Warn("Cannot convert result to json ", result)
  47. }
  48. m.w.Header().Set("Content-Type", "text/json; charset=utf-8")
  49. //apiV1AddTrackingCookie(w, r, ss) //always the last one to set cookies
  50. fmt.Fprint(m.w, string(out))
  51. }
  52. func sendContactUs(name string, email string, userInput string) {
  53. // Sender data.
  54. from := "mailer@biukop.com.au"
  55. password := "hpfitsrujgkewcdw"
  56. // Receiver email address.
  57. to := []string{
  58. "patrick@biukop.com.au",
  59. }
  60. // smtp server configuration.
  61. smtpHost := "smtp.gmail.com"
  62. smtpPort := "587"
  63. raw := `Subject: {name} [ Contact form on Biukop Web ]
  64. Content-Type: text/plain; charset="UTF-8"
  65. Dear Manager,
  66. We received a a form submission from biukop.com.au
  67. name : {name}
  68. email : {email}
  69. message:
  70. {message}
  71. Kind Regards
  72. Biukop Mailing service team.
  73. `
  74. raw = strings.Replace(raw, "{name}", name, -1)
  75. raw = strings.Replace(raw, "{email}", email, -1)
  76. raw = strings.Replace(raw, "{message}", userInput, -1)
  77. // Message.
  78. message := []byte(raw)
  79. // Authentication.
  80. auth := smtp.PlainAuth("", from, password, smtpHost)
  81. // Sending email.
  82. err := smtp.SendMail(smtpHost+":"+smtpPort, auth, from, to, message)
  83. if err != nil {
  84. fmt.Println(err)
  85. return
  86. }
  87. fmt.Println("Email Sent Successfully!")
  88. }