To my surprise I did not find a contact form mail handler example for go? I don't feel like making a wheel today, are there examples available?
EDIT: (cut and paste answer)
package bin
import (
"fmt"
"net/http"
netMail "net/mail"
"appengine"
"appengine/mail"
)
func contact(w http.ResponseWriter, r *http.Request) {
c := appengine.NewContext(r)
name := r.FormValue("name")
email := r.FormValue("email")
subject := r.FormValue("subject")
message := r.FormValue("message")
msg := &mail.Message{
Sender: name + " <...@yourappid.appspotmail.com>",
To: []string{"...@..."},
ReplyTo: email,
Subject: subject,
Body: message,
Headers: netMail.Header{
"On-Behalf-Of": []string{email},
},
}
if err := mail.Send(c, msg); err != nil {
c.Errorf("Couldn't send email: %v", err)
fmt.Fprint(w, "Mail NOT send! Error")
}else{
fmt.Fprint(w, "Mail send.")
}
}
NOTE:
1) ReplyTo
only works in gmail if Sender
and To
are different.
2) Sender
should have admin role in google cloud console or something@yourappid.appspotmail.com
.
This is most likely failing because the Sender
can only be
something@yourappid.appspotmail.com
I suggest that you hard-code the sender's email, and use the On-Behalf-Of
header in which you include the original sender's name/email.
Also, WriteString
accepts a single string
, not a []string
slice.
The minimum modifications for your example would be:
…
msg := &mail.Message{
Sender: name + " <developer@yourapp.com>",
To: []string{"...@gmail.com"},
Subject: subject,
Body: message,
Headers: netMail.Header{
"On-Behalf-Of": []string{email},
},
}
…
Also, you'll need to make sure the user's name doesn't actually contain an email address. That could cause you problems…
The best would be to do as @elithrar suggested and validate your form.