Many of you at the “free” Go programming course have been asking “How do I use Gmail with Go?” To answer that question, we will quickly build a fun Go web app that uses Gmail to send off emails.
I am assuming that you have downloaded and installed Go and have set the GOPATH
properly. If new to Go, then my previous article has this covered.
Sign up for a free Gmail account, if you don’t have one already.
In one of my previous articles, we learned about Golang’s package template (namely text/template
and html/template
). We shall use html/template
here. Also, we shall use Golang’s net/smtp package to connect to Gmail.
Create the folder C:/go_projects/go/src/github.com/SatishTalim/webgmail
. In this folder, create a file webgmail.go
as follows:
package main import ( "fmt" "html/template" "net/http" "net/smtp" "os" ) func main() { http.HandleFunc("/", root) http.HandleFunc("/mail", mail) fmt.Println("listening...") err := http.ListenAndServe(GetPort(), nil) if err != nil { panic(err) } } func GetPort() string { var port = os.Getenv("PORT") // Set a default port if there is nothing in the environment if port == "" { port = "4747" fmt.Println("INFO: No PORT environment variable detected, defaulting to " + port) } return ":" + port } func root(w http.ResponseWriter, r *http.Request) { fmt.Fprint(w, rootForm) } const rootForm = ` <!DOCTYPE html> <html> <head> <meta charset="utf-8"> <title>Enter your mail</title> <link rel="stylesheet" href="http://yui.yahooapis.com/pure/0.4.2/pure-min.css"> </head> <body> <h2>Enter your Email</h2> <form action="/mail" method="post" accept-charset="utf-8" class="pure-form"> To:<input type="text" name="to" /> Subject<:input type="text" name="subject" /> Message:<input type="text" name="msg" /> <input type="submit" value="... and check the mail!" class="pure-button pure-button-primary" /> </form> <div> <p><b>© 2014 RubyLearning. All rights reserved.</b></p> </div> </body> </html> ` const mailTemplateHTML = ` <!DOCTYPE html> <html> <head> <meta charset="utf-8"> <title>Email Result</title> <link rel="stylesheet" href="http://yui.yahooapis.com/pure/0.4.2/pure-min.css"> </head> <body> <h2>Email Result</h2> <p>Your email has been sent to: </p> <pre>{{html .}}</pre> <p><a href="/">Start again!</a></p> <div> <p><b>© 2014 RubyLearning. All rights reserved.</b></p> </div> </body> </html> ` var mailTemplate = template.Must(template.New("mail").Parse(mailTemplateHTML)) func mail(w http.ResponseWriter, r *http.Request) { to := r.FormValue("to") subject := r.FormValue("subject") message := r.FormValue("msg") body := "To: " + to + "\r\nSubject: " + subject + "\r\n\r\n" + message auth := smtp.PlainAuth("", "satish.talim", "password", "smtp.gmail.com") err := smtp.SendMail("smtp.gmail.com:587", auth, "satish.talim@gmail.com", []string{to},[]byte(body)) if err != nil { panic(err) } err1 := mailTemplate.Execute(w, to) if err1 != nil { http.Error(w, err1.Error(), http.StatusInternalServerError) } }
From the folder C:/go_projects/go/src/github.com/SatishTalim/webgmail
you can now run the program by typing:
$ go run webgmail.go
Point your browser to http://localhost:4747 and you should see something like this in your browser:
Note:
- You call smtp.PlainAuth with your gmail username, password and domain name, and it returns you back an instance of smtp.Auth that you can use to send e-mails.
- If you have setup the 2-Step Verification process in Gmail, then you need to set an application-specific password. Use this password in the above program.
- You can send mail with smtp.SendMail.
- SMTP on port 587 uses TLS. SSL and TLS both provide a way to encrypt a communication channel between two computers (e.g. your computer and a server). TLS is the successor to SSL and the terms SSL and TLS are used interchangeably unless you’re referring to a specific version of the protocol.
You can learn more about writing and deploying web apps with Go from my new book.
I hope you’ve enjoyed this post, please leave any feedback in the comments section.
One thought on “Fun with Gmail and Go”