为了账号安全,请及时绑定邮箱和手机立即绑定

使用 Gomail 创建联系表单

使用 Gomail 创建联系表单

Go
守候你守候我 2022-01-04 10:31:35
我目前正在学习 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 mainimport (    "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}基本上它的作用是提供索引页面(联系表格)和确认页面。它还定义了Email和Contact字符串。如果我想打印消息的内容,我可以只使用m.Content,但是由于 Gomail 要求提供正文并提供 html,我真的不知道如何从表单中获取字符串并像这样添加它:m.SetBody("text/html", "<b>Message</b>: <!-- Content Goes Here -->")`
查看完整描述

1 回答

?
慕容森

TA贡献1853条经验 获得超18个赞

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

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


查看完整回答
反对 回复 2022-01-04
  • 1 回答
  • 0 关注
  • 269 浏览
慕课专栏
更多

添加回答

举报

0/150
提交
取消
微信客服

购课补贴
联系客服咨询优惠详情

帮助反馈 APP下载

慕课网APP
您的移动学习伙伴

公众号

扫描二维码
关注慕课网微信公众号