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
| // Define types
type EmailBody struct {
Personalizations []EmailPersonalization `json:"personalizations"`
From EmailIdentifier `json:"from"`
Subject string `json:"subject"`
Content []EmailContent `json:"content"`
}
type EmailPersonalization struct {
To []EmailIdentifier `json:"to"`
Substitutions map[string]string `json:"substitutions"`
}
type EmailIdentifier struct {
Email string `json:"email"`
Name string `json:"name"`
}
type EmailContent struct {
Type string `json:"type"`
Value string `json:"value"`
}
// Send an email
emailBody := &EmailBody{
Personalizations: []EmailPersonalization{
{
To: []EmailIdentifier{
{
Email: "tom@example.com",
Name: "Tom",
},
},
Substitutions: map[string]string{
"-name-": "Tom",
},
},
{
To: []EmailIdentifier{
{
Email: "sean@example.com",
Name: "Sean",
},
},
Substitutions: map[string]string{
"-name-": "Sean",
},
},
},
From: EmailIdentifier{
Email: "no-reply@awesomegame.com",
Name: "Awesome Game",
},
Subject: "Login now to receive your Daily Login Reward!",
Content: []EmailContent{
{
Type: "text/html",
Value: `<p>
Hello, -name-!<br />
Login to Awesome Game now to receive your Daily Login Reward of 1000 Awesome Coins!
</p>`,
},
},
}
jsonBody, err := json.Marshal(emailBody)
if err != nil {
logger.Error("error marshaling email body", err)
return err
}
request, err := http.NewRequest("post", "https://api.sendgrid.com/v3/mail/send", bytes.NewBuffer(jsonBody))
request.Header.Set("Content-Type", "application/json")
request.Header.Set("Authorization", "Bearer <YourSendgridApiKey>")
client := &http.Client{}
response, err := client.Do(request)
defer response.Body.Close()
if err != nil {
logger.Error("error making HTTP post", err)
return err
}
if response.StatusCode != 202 {
logger.Warn("failed to send email", err)
} else {
logger.Info("successfully sent email")
}
|