forked from GoogleCloudPlatform/golang-samples
-
Notifications
You must be signed in to change notification settings - Fork 0
/
mailgun.go
90 lines (75 loc) · 2.31 KB
/
mailgun.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
79
80
81
82
83
84
85
86
87
88
89
90
// 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 mailgun is a demonstration on sending an e-mail from App Engine flexible environment.
package main
import (
"fmt"
"io/ioutil"
"log"
"net/http"
"os"
"strings"
"github.com/mailgun/mailgun-go"
"google.golang.org/appengine"
)
func main() {
http.HandleFunc("/send_simple", sendSimpleMessageHandler)
http.HandleFunc("/send_complex", sendComplexMessageHandler)
appengine.Main()
}
var (
mailgunClient mailgun.Mailgun
mailgunDomain string
)
func init() {
mailgunDomain = mustGetenv("MAILGUN_DOMAIN_NAME")
mailgunClient = mailgun.NewMailgun(
mailgunDomain,
mustGetenv("MAILGUN_API_KEY"))
}
func mustGetenv(k string) string {
v := os.Getenv(k)
if v == "" {
log.Fatalf("%s environment variable not set.", k)
}
return v
}
// [START gae_flex_mailgun_simple_message]
func sendSimpleMessageHandler(w http.ResponseWriter, r *http.Request) {
msg, id, err := mailgunClient.Send(mailgunClient.NewMessage(
/* From */ fmt.Sprintf("Excited User <mailgun@%s>", mailgunDomain),
/* Subject */ "Hello",
/* Body */ "Testing some Mailgun awesomness!",
/* To */ "[email protected]", "YOU@"+mailgunDomain,
))
if err != nil {
msg := fmt.Sprintf("Could not send message: %v, ID %v, %+v", err, id, msg)
http.Error(w, msg, http.StatusInternalServerError)
return
}
w.Write([]byte("Message sent!"))
}
// [END gae_flex_mailgun_simple_message]
// [START gae_flex_mailgun_complex_message]
func sendComplexMessageHandler(w http.ResponseWriter, r *http.Request) {
message := mailgunClient.NewMessage(
/* From */ fmt.Sprintf("Excited User <mailgun@%s>", mailgunDomain),
/* Subject */ "Hello",
/* Body */ "Testing some Mailgun awesomness!",
/* To */ "[email protected]",
)
message.AddCC("[email protected]")
message.AddBCC("[email protected]")
message.SetHtml("<html>HTML version of the body</html>")
message.AddReaderAttachment("files/test.txt",
ioutil.NopCloser(strings.NewReader("foo")))
msg, id, err := mailgunClient.Send(message)
if err != nil {
msg := fmt.Sprintf("Could not send message: %v, ID %v, %+v", err, id, msg)
http.Error(w, msg, http.StatusInternalServerError)
return
}
w.Write([]byte("Message sent!"))
}
// [END gae_flex_mailgun_complex_message]