forked from xinyunh0929/golang-samples
-
Notifications
You must be signed in to change notification settings - Fork 1
/
sendgrid.go
51 lines (39 loc) · 1.16 KB
/
sendgrid.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
// Copyright 2015 Google Inc. All rights reserved.
// Use of this source code is governed by the Apache 2.0
// license that can be found in the LICENSE file.
// Sample sendgrid is a demonstration on sending an e-mail from App Engine flexible environment.
package main
import (
"fmt"
"log"
"net/http"
"os"
"google.golang.org/appengine"
)
// [START import]
import "gopkg.in/sendgrid/sendgrid-go.v2"
// [END import]
func main() {
http.HandleFunc("/sendmail", sendMailHandler)
appengine.Main()
}
var sendgridClient *sendgrid.SGClient
func init() {
sendgridKey := os.Getenv("SENDGRID_API_KEY")
if sendgridKey == "" {
log.Fatal("SENDGRID_API_KEY environment variable not set.")
}
sendgridClient = sendgrid.NewSendGridClientWithApiKey(sendgridKey)
}
func sendMailHandler(w http.ResponseWriter, r *http.Request) {
m := sendgrid.NewMail()
m.AddTo("[email protected]")
m.SetSubject("Email From SendGrid")
m.SetHTML("Through AppEngine")
m.SetFrom("[email protected]")
if err := sendgridClient.Send(m); err != nil {
http.Error(w, fmt.Sprintf("could not send mail: %v", err), http.StatusInternalServerError)
return
}
fmt.Fprintf(w, "email sent successfully.")
}