0
私は現在Goを学習しており、連絡先フォームを作成しようとしています。私はメールを送るためにデフォルトのnet/smtp
パッケージを使用していましたが、その後私はGomailを見つけました。それは電子メールを送ることをずっと容易にしました。私は値を取得するために行くのhtml/template
パッケージを使用していGomailで連絡先フォームを作成する
<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>
:ここ
は、お問い合わせフォームのHTMLです。
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 <[email protected]>")
m.SetHeader("To", "John Smith <[email protected]>")
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, "[email protected]", "password")
if err := d.DialAndSend(m); err != nil {
panic(err)
}
}
は、基本的にこれが何をするかインデックスページ(お問い合わせフォーム)と確認ページを提供しています。 Email
とContact
の文字列も定義します。メッセージの内容を印刷したいのであれば、m.Content
を使用することができますが、Gomailが本文を検索してhtmlを提供するので、フォームから文字列を取得して次のように追加する方法はわかりません。
m.SetBody("text/html", "<b>Message</b>: <!-- Content Goes Here -->")`
答えてくれてありがとうございました。コンパイラとの混乱を避けるため、m.Contentをmsg.Contentに変更しなければなりませんでした。これは私のコードをhttp://pastebin.com/raw/TxZPmiw6に変更しなければならなかったものです。今コンパイルすると './main.go:59:undefined:msg in msg.Content'が返されます。 – cmelone
send関数でメッセージ構造体をインスタンス化しているので、未定義のエラーが発生しています。構造体をメインの実行スレッドに移動する必要があります。私は 'Deliver' funcが開始時に実行されていると思います。 –
'Message'構造体をmain関数(https://git.io/vVSXR0)に追加すると、次のエラーが発生します:' ./main.go:29:undefined:msg in msg.Content ./ main.go:43:undefined:メッセージ ' – cmelone