使用Gomail创建联系表单

huangapple go评论83阅读模式
英文:

Creating a contact form with 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() {
	msg := gomail.NewMessage()
	msg.SetHeader("From", "John Smith <jsmith@gmail.com>")
	msg.SetHeader("To", "John Smith <jsmith@gmail.com>")
	msg.SetAddressHeader("reply-to", m.Email)
	msg.SetHeader("Subject", "Contact")
	msg.SetBody("text/html", "<b>Message</b>: "+m.Content)
	d := gomail.NewDialer("smtp.gmail.com", 587, "jsmith@gmail.com", "password")
	if err := d.DialAndSend(msg); err != nil {
		panic(err)
	}
}

基本上,这段代码会提供索引页面(即联系表单)和确认页面。它还定义了EmailContent字符串。如果我想要打印出消息的内容,我可以使用m.Content,但由于Gomail要求提供邮件正文并提供HTML,我不知道如何从表单中获取字符串并像这样添加:

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

以上是你要翻译的内容。

英文:

I am currently learning Go, and I am trying to create a contact form. I was using the default net/smtp package to send my mail, but then I stumbled upon Gomail. It made it so much easier to send an email.

Here is the html for the contact form:

&lt;h1&gt;Contact Us&lt;/h1&gt;
&lt;form action=&quot;/&quot; method=&quot;post&quot; novalidate&gt;
&lt;div&gt;
&lt;label&gt;Email Address&lt;/label&gt;
&lt;input type=&quot;email&quot; name=&quot;email&quot; value=&quot;{{ .Email }}&quot;&gt;
&lt;/div&gt;
&lt;div&gt;
&lt;label&gt;Message:&lt;/label&gt;
&lt;textarea name=&quot;content&quot;&gt;{{ .Content }}&lt;/textarea&gt;
&lt;/div&gt;
&lt;div&gt;
&lt;input type=&quot;submit&quot; value=&quot;Submit&quot;&gt;
&lt;/div&gt;
&lt;/form&gt;

I'm using Go's html/template package to get the values.

main.go:

package main
import (
&quot;fmt&quot;
&quot;github.com/bmizerany/pat&quot;
&quot;gopkg.in/gomail.v2&quot;
&quot;html/template&quot;
&quot;log&quot;
&quot;net/http&quot;
)
func main() {
mux := pat.New()
mux.Get(&quot;/&quot;, http.HandlerFunc(index))
mux.Post(&quot;/&quot;, http.HandlerFunc(send))
mux.Get(&quot;/confirmation&quot;, http.HandlerFunc(confirmation))
log.Println(&quot;Listening...&quot;)
http.ListenAndServe(&quot;:2016&quot;, mux)
}
func index(w http.ResponseWriter, r *http.Request) {
render(w, &quot;templates/index.html&quot;, nil)
}
func send(w http.ResponseWriter, r *http.Request) {
m := &amp;Message{
Email: r.FormValue(&quot;email&quot;),
Content: r.FormValue(&quot;content&quot;),
}
if err := m.Deliver(); err != nil {
http.Error(w, err.Error(), http.StatusInternalServerError)
return
}
http.Redirect(w, r, &quot;/confirmation&quot;, http.StatusSeeOther)
}
func confirmation(w http.ResponseWriter, r *http.Request) {
render(w, &quot;templates/confirmation.html&quot;, 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(&quot;From&quot;, &quot;John Smith &lt;jsmith@gmail.com&gt;&quot;)
m.SetHeader(&quot;To&quot;, &quot;John Smith &lt;jsmith@gmail.com&gt;&quot;)
m.SetAddressHeader(&quot;reply-to&quot;, &quot;m.Email&quot;)
m.SetHeader(&quot;Subject&quot;, &quot;Contact&quot;)
m.SetBody(&quot;text/html&quot;, &quot;&lt;b&gt;Message&lt;/b&gt;: m.Content&quot;)
d := gomail.NewDialer(&quot;smtp.gmail.com&quot;, 587, &quot;jsmith@gmail.com&quot;, &quot;password&quot;)
if err := d.DialAndSend(m); err != nil {
panic(err)
}
}

Basically what this does is serve the index page (the contact form) and the confirmation page. It also defines the Email and Contact strings. If I wanted to print out the content of the message, I can just use m.Content, but since Gomail asks for the body and serves html, I don't really know a way to get the string from the form and add it like this:

m.SetBody(&quot;text/html&quot;, &quot;&lt;b&gt;Message&lt;/b&gt;: &lt;!-- Content Goes Here --&gt;&quot;)`

答案1

得分: 1

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

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

In this case what you can do, is to use the Sprintf formatting method. In your particular case:

m.SetBody(&quot;text/html&quot;, fmt.Sprintf(&quot;&lt;b&gt;Message&lt;/b&gt;: %s&quot;, m.Content))

huangapple
  • 本文由 发表于 2016年4月10日 13:45:36
  • 转载请务必保留本文链接:https://go.coder-hub.com/36526304.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定