forked from GoogleCloudPlatform/golang-samples
-
Notifications
You must be signed in to change notification settings - Fork 0
/
mailjet.go
78 lines (62 loc) · 1.73 KB
/
mailjet.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
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
// Copyright 2016 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 mailjet is a demonstration on sending an e-mail from App Engine standard environment.
package mailjet
import (
"fmt"
"log"
"net/http"
"os"
"google.golang.org/appengine"
"google.golang.org/appengine/urlfetch"
)
// [START import]
import "github.com/mailjet/mailjet-apiv3-go"
// [END import]
func init() {
// Check env variables are set.
mustGetenv("MJ_APIKEY_PUBLIC")
mustGetenv("MJ_APIKEY_PRIVATE")
http.HandleFunc("/send", sendEmail)
}
var fromEmail = mustGetenv("MJ_FROM_EMAIL")
func mustGetenv(k string) string {
v := os.Getenv(k)
if v == "" {
log.Fatalf("%s environment variable not set.", k)
}
return v
}
func sendEmail(w http.ResponseWriter, r *http.Request) {
ctx := appengine.NewContext(r)
mailjetClient := mailjet.NewMailjetClient(
mustGetenv("MJ_APIKEY_PUBLIC"),
mustGetenv("MJ_APIKEY_PRIVATE"),
)
mailjetClient.SetClient(urlfetch.Client(ctx))
to := r.FormValue("to")
if to == "" {
http.Error(w, "Missing 'to' parameter.", http.StatusBadRequest)
return
}
m := &mailjet.InfoSendMail{
FromEmail: fromEmail,
FromName: "App Engine Mailjet sample",
Subject: "Your email flight plan!",
TextPart: "Dear passenger, welcome to Mailjet! May the delivery force be with you!",
HTMLPart: "<h3>Dear passenger, welcome to Mailjet!</h3><br/>May the delivery force be with you!",
Recipients: []mailjet.Recipient{
{
Email: to,
},
},
}
resp, err := mailjetClient.SendMail(m)
if err != nil {
msg := fmt.Sprintf("Could not send mail: %v", err)
http.Error(w, msg, 500)
return
}
fmt.Fprintf(w, "%d email(s) sent!", len(resp.Sent))
}