使用Gomail创建联系表单

时间:2016-04-10 05:45:36

标签: forms go gomail

我正在学习Go,我正在尝试创建一个联系表单。我使用默认的net/smtp包来发送邮件,但后来我偶然发现了Gomail。它使发送电子邮件变得更加容易。

以下是联系表单的HTML

<h1>Contact Us</h1>
<form action="/" method="post" novalidate>
  <div>
    <label>Email Address</label>
    <input type="email" name="email" value="{{ .Email }}">
  </div>
  <div>
    <label>Message:</label>
    <textarea name="content">{{ .Content }}</textarea>
  </div>
  <div>
    <input type="submit" value="Submit">
  </div>
</form>

我正在使用Go的html/template包来获取值。

main.go

package main

import (
    "fmt"
    "github.com/bmizerany/pat"
    "gopkg.in/gomail.v2"
    "html/template"
    "log"
    "net/http"
)

func main() {
    mux := pat.New()
    mux.Get("/", http.HandlerFunc(index))
    mux.Post("/", http.HandlerFunc(send))
    mux.Get("/confirmation", http.HandlerFunc(confirmation))

    log.Println("Listening...")
    http.ListenAndServe(":2016", mux)
}

func index(w http.ResponseWriter, r *http.Request) {
    render(w, "templates/index.html", nil)
}

func send(w http.ResponseWriter, r *http.Request) {
  m := &Message{
    Email: r.FormValue("email"),
    Content: r.FormValue("content"),
  }

  if err := m.Deliver(); err != nil {
    http.Error(w, err.Error(), http.StatusInternalServerError)
    return
  }
  http.Redirect(w, r, "/confirmation", http.StatusSeeOther)
}

func confirmation(w http.ResponseWriter, r *http.Request) {
    render(w, "templates/confirmation.html", nil)
}

func render(w http.ResponseWriter, filename string, data interface{}) {
    tmpl, err := template.ParseFiles(filename)
    if err != nil {
        http.Error(w, err.Error(), http.StatusInternalServerError)
    }
    if err := tmpl.Execute(w, data); err != nil {
        http.Error(w, err.Error(), http.StatusInternalServerError)
    }
}

type Message struct {
    Email   string
    Content string
}

func (m *Message) Deliver() {
    m := gomail.NewMessage()
    m.SetHeader("From", "John Smith <jsmith@gmail.com>")
    m.SetHeader("To", "John Smith <jsmith@gmail.com>")
    m.SetAddressHeader("reply-to", "m.Email")
    m.SetHeader("Subject", "Contact")
    m.SetBody("text/html", "<b>Message</b>: m.Content")
    d := gomail.NewDialer("smtp.gmail.com", 587, "jsmith@gmail.com", "password")
    if err := d.DialAndSend(m); err != nil {
        panic(err)
    }
}

这基本上是为索引页面(联系表单)和确认页面提供服务。它还定义了EmailContact字符串。如果我想打印出消息的内容,我可以使用m.Content,但是由于Gomail请求正文并提供html,我真的不知道从表单中获取字符串并添加的方法它是这样的:

m.SetBody("text/html", "<b>Message</b>: <!-- Content Goes Here -->")`

1 个答案:

答案 0 :(得分:1)

在这种情况下,您可以使用Sprintf格式化方法。在您的特定情况下:

m.SetBody("text/html", fmt.Sprintf("<b>Message</b>: %s", m.Content))